5 common mistakes made by beginner python programmers

During the initial days as python programmer, all of us face some or other type of weird bug in our code which, after spending multiple painful hours on Stackoverflow, turns out to be not a bug but python feature. That's how things works in python. So below are the 5 most common mistakes most of the beginner python programmers make. Lets know a bit about them so that we can save few hours of asking questions on Facebook pages and groups.  


1. Creating a copy of dictionary or lists.


Whenever you need to make a copy of a dictionary or list, do not simply use the assignment operator.

wrong way:

>>> dict_a = {"name": "John", "address":"221B Baker street"}
>>> dict_b = dict_a


Now if you edit/update the dict_b , dict_a  will also be updated because by using assignment operator, you are trying to say that dict_b  will point to the same object to which dict_a  is pointing.

>>> dict_b["age"] = 26
>>> dict_b
{'address': '221B Baker street', 'name': 'John', 'age': 26}
>>> dict_a
{'address': '221B Baker street', 'name': 'John', 'age': 26}
>>> 


Right way: Use the copy()  or deepcopy()  method.

>>> dict_c = dict_b.copy()
>>> dict_c["location"] = "somewhere"
>>> dict_c
{'address': '221B Baker street', 'name': 'John', 'age': 26, 'location': 'somewhere'}
>>> dict_b
{'address': '221B Baker street', 'name': 'John', 'age': 26}
>>> dict_a
{'address': '221B Baker street', 'name': 'John', 'age': 26}
>>> 


See the difference between copy and deepcopy.


2. Dictionary keys.


Lets say we put the below values in a dictionary.

>>> dict_a = dict()
>>> dict_a
{}
>>> dict_a[1] = "apple"
>>> dict_a[True] = "mango"
>>> dict_a[2] = "melon"


If we try to print the dictionary, what will be the output. Let's see.

>>> dict_a
{1: 'mango', 2: 'melon'}

What just happened? where is the key True ?

Remember Boolean class is the subclass of Integer. Integer equivalent of True is 1 and that of False is 0. Hence value of key 1 is overwritten.

>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> True == 1
True
>>> False == 0
True
>>> 
 


3. Updating lists or dictionaries.


Lets say you want to append an item to the list.

>>> list_a = [1,2,3,4,5]
>>> list_a = list_a.append(6)
>>> list_a
>>> # prints nothing


Try to update a dictionary.

>>> dict_a = {"a" : "b"}
>>> dict_a = dict_a.update({"c" : "d"})
>>> dict_a
>>> # prints nothing


Ok, lets try to sort a list.

>>> list_b = [2,5,3,1,7]
>>> list_b = list_b.sort()
>>> list_b
>>> # prints nothing


Why nothing is being printed? What are we doing wrong?

Most the sequence object methods like sort, update, append, add etc works in place to increase performance by avoiding to create a separate copy un-necessarily.

Do not try to assign the output of such methods to variable.

Right way:

>>> list_a = [1,2,3,4,5]
>>> list_a.append(6)
>>> dict_a = {"a" : "b"}
>>> dict_a.update({"c" : "d"})
>>> dict_a
{'c': 'd', 'a': 'b'}
>>> list_a.sort()
>>> list_a
[1, 2, 3, 4, 5, 6]
 

4.  Interned Strings.

In some cases, python try to reuse the existing immutable objects. String interning is one such case.

>>> a = "gmail"
>>> b = "gmail"
>>> a is b
True


Here we tried to create two different string objects. But when checked if both the objects are same, it returned True. This is because python didn't created another object b  but pointed the b to the first value "gmail".

All strings of length 1 are interned. String having anything except ASCII characters, digits and underscore in them are not interned.

Let's see.

>>> a = "@gmail"
>>> b = "@gmail"
>>> a is b
False
>>> 


Also remember ==  is different than is  operator. ==  checks if values are equal or not while is  checks if both variable are pointing to same object.

>>> a = "@gmail"
>>> b = "@gmail"
>>> a is b
False
>>> a == b
True
>>> 


So keep the above point in mind while using immutable strings or ==  or is  operator.  


5. Default arguments are evaluated only once.


Consider below example.

def func(a, lst=[]):
    lst.append(a)
    return lst

print(func(1))
print(func(2))


What do you think will be the output of above two print statements?

Lets try to run it.

>>> def func(a, lst=[]):
...     lst.append(a)
...     return lst
... 
>>> print(func(1))
[1]
>>> print(func(2))
[1, 2]
>>> 


Why the output is [1,2]  in second case. Shouldn't it be just [2] ?

So the catch here is, default arguments of a function are evaluated just once. On first call i.e  func(1) , list lst  is evaluated and is found empty hence 1 is appended to it. But on second call, list is already having one element hence output is [1,2]  


Bonus: Don't mix spaces and tabs. Just don't. You will cry.


Please comment if you find something is not correct.



Related Articles:
What is the meaning of different aphorism in zen of python
What is zen of python. What is the meaning of zen of python. Explanation of zen of python terms with example. Easter egg Zen of python. import this....
Displaying custom 404 error (page not found) page in Django 2.0
How to create custom 404 error page in Django. Handler404 example Django 2.0. Page not found error in Django 2.0. Custom Error handlers in Django 2.0...
How to share data between two systems using python simple HTTP server
How to share large files between two system using python simple HTTP server. share movies using python server. transfer data without pen drive using python....
Designing custom 404 and 500 error pages in Django
How to create your own awesome 404 error or 500 error page in django. Step by step guide to help you design your own 404 not found error page in Django. Design your own 500 internal server error page in Django application...

0 thoughts on '5 Common Mistakes Made By Beginner Python Programmers'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019