18 Essential Python tricks

  1. Get file path of imported modules

>> import os
>>> print os
<module ‘os’ from ‘/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc’>
>>>

2. Get memory usage of an object

>> import sys
>>> var = 10
>>> print sys.getsizeof(var)
24
>>>

3. Print string n times

>> sample=”Python”
>>> n=4
>>> print sample*n
PythonPythonPythonPython
>>>

4. swapping of two numbers

>> a=10
>>> b=20
>>> a
10
>>> b
20
>>> a,b = b,a
>>> a
20
>>> b
10
>>>

5.Reverse a string

>> sample = “Python”
>>> sample[::-1]
‘nohtyP’
>>>

6. Return multiple values from function

>> def foo():
… return 10, 20

>>> x, y = foo()
>>> x
10
>>> y
20
>>>

7. Create string from list

>> list_str = [“Python”, “is”, “awesome”]
>>> ” “.join(list_str)
‘Python is awesome’
>>>

8. Transpose a matrix

>> mtx = [ [1,2,3], [4,5,6], [7,8,9] ]
>>> zip(*mtx)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>

9. Assign list elements to multiple variables

>> x, y, z = [10,20,30]
>>> x
10
>>> y
20
>>> z
30
>>>

10. Zipping two lists

>> x = [1, 2, 3]
>>> y = [‘a’, ‘b’, ‘c’]
>>> for i in zip(x,y): print i

(1, ‘a’)
(2, ‘b’)
(3, ‘c’)
>>> z=zip(x,y)
>>> z
[(1, ‘a’), (2, ‘b’), (3, ‘c’)]
>>>

11. Create single list out of list of lists

>> x = [[1, 2], [3, 4], [5, 6]]
>>> import itertools
>>> list(itertools.chain.from_iterable(x))
[1, 2, 3, 4, 5, 6]
>>>

12. check if two strings are anagrams

>> from collections import Counter
>>> def is_anagram(string1, string2):
… return Counter(string1) == Counter(string2)

>>> is_anagram(“xyzw”, “zywx”)
True
>>> is_anagram(“xyzw”, “zyx”)
False
>>>

13. Taking stdin as list of int

>> x = map(int, raw_input().split())
1 2 3 4 5 6
>>> x
[1, 2, 3, 4, 5, 6]
>>>

14. Ternary operator for conditional assignment

>> a = 2
>>> is_even = True if a % 2 == 0 else False
>>> is_even
True
>>> a=3
>>> is_even = True if a % 2 == 0 else False
>>> is_even
False
>>>

>> [ x**3 if x%2 != 0 else 0 for x in range(9)]
[0, 1, 0, 27, 0, 125, 0, 343, 0]
>>>

15. “_” operator : references last executed operations

>> a = 10
>>> b= 20
>>> _
[0, 1, 0, 27, 0, 125, 0, 343, 0]
>>>
>>> a+b
30
>>> a-b
-10
>>> _
-10
>>>

16. Run simple http server

Hindons-MacBook-Air:~ hindon$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 …

17. Inspect an object

>> x=10
>>> dir(x)
[‘__abs__’, ‘__add__’, ‘__and__’, ‘__class__’, ‘__cmp__’, ‘__coerce__’, ‘__delattr__’, ‘__div__’, ‘__divmod__’, ‘__doc__’, ‘__float__’, ‘__floordiv__’, ‘__format__’, ‘__getattribute__’, ‘__getnewargs__’, ‘__hash__’, ‘__hex__’, ‘__index__’, ‘__init__’, ‘__int__’, ‘__invert__’, ‘__long__’, ‘__lshift__’, ‘__mod__’, ‘__mul__’, ‘__neg__’, ‘__new__’, ‘__nonzero__’, ‘__oct__’, ‘__or__’, ‘__pos__’, ‘__pow__’, ‘__radd__’, ‘__rand__’, ‘__rdiv__’, ‘__rdivmod__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rfloordiv__’, ‘__rlshift__’, ‘__rmod__’, ‘__rmul__’, ‘__ror__’, ‘__rpow__’, ‘__rrshift__’, ‘__rshift__’, ‘__rsub__’, ‘__rtruediv__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__truediv__’, ‘__trunc__’, ‘__xor__’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘imag’, ‘numerator’, ‘real’]
>>>

18. Create dictionary from two lists

>> x = [1,2,3]
>>> y=[‘a1′,’b1′,’c1’]
>>> dict(zip(x,y))
{1: ‘a1’, 2: ‘b1’, 3: ‘c1’}
>>>