Nifty Python tricks — Yasoob Khalid

Hi there folks. It’s been a long time since I last published a post. I have been busy. However in this post I am going to share some really informative tips and tricks which you might not have known about. So without wasting any time lets get straight to them:
Enumerate
Instead of doing:
i = 0
for item in iterable:
print i, item
i += 1
We can do:
for i, item in enumerate(iterable):
print i, item
Enumerate can also take a second argument. Here is an example:
>>> list(enumerate(‘abc’))
>>> list(enumerate(‘abc’, 1))
Dict/Set comprehensions
You might know about list comprehensions but you might not be aware of dict/set comprehensions. They are simple to use and just as effective. Here is an example:
my_dict = {i: i * i for i in xrange(100)}
my_set = {i * 15 for i in xrange(100)}
# There is only a difference of ‘:’ in both
Forcing float division:
If we divide whole numbers Python gives us the result as a whole number even if the result was a float. In order to circumvent this issue we have to do something like this:
result = 1.0/2
But there is another way to solve this problem which even I wasn’t aware of. You can do:
from __future__ import division
result = 1/2
# print(result)
# 0.5
Voila! Now you don’t need to append .0 in order to get an accurate answer. Do note that this trick is for Python 2 only. In Python 3 there is no need to do the import as it handles this case by default.