Some cool tricks you might be unaware of (especially for beginners). Actually, there are hundreds of such cool tricks but I tried to avoid those which needed importing of various modules or which used rather advanced topics. Python 2.7 is assumed. More will be added later.

  • Finding the list of builtin:
def func():

Alternatively, you can also do this:

  • dir can also be used for built in types like this:
dir('') # for string
dir([]) # for list
dir({}) # for dictionary
  • Use__doc__ for documentation:
import sys
#output- details about sys module
  • Finding the list of keywords:
import keyword
print keyword.kwlist
  • Help on operator precedence:
  • Where are you?:
#output- '__main__'
  • Use of ‘,’ while iterating in ‘for’ block:
foo = [1,2,3]
for i in foo:
....print i, #also repeat the same by removing comma
#output- 1 2 3
  • Tricks for working with lists:
s = list(range(10))
print s[::2] #output = [0,2,4,6,8]
print s[::-1] #output = [9,8,7,6,5,4,3,2,1,0]
  • enumerate function
a = ['a', 'b', 'c', 'd', 'e']
for index, item in enumerate(a, start=1): print index, item
1 a
2 b
3 c
4 d
5 e
# if 'start' parameter is ignored,indexing would start from 0.
  • Converting integers in a list into string:
s = [1,2,3,4,5]
#output- ['1','2','3','4','5']
  • Starting simple HTTP server. It comes handy if you want to transfer files to some other systems.
python -m simpleHTTPserver
# output - serving HTTP on port 8000...
  • Zipping two list like this:
name = ['Richard', 'Sam']
surname = ['Dawkins', 'Harris']
print zip(name, surname)
# output- [('Richrad', 'Dawkins'), ('Sam', 'Harris')]
print dict(zip(name, surname))
# output- {'Richrad': 'Dawkins', 'Sam': 'Harris'}
  • When a function returns a list but you know that this list has only one element so you may want that element rather than the list containing the element. You may do this:
word = 'm'
result = list(word)[0]
print result
#output- m

But you can also do this:

word = 'm'
result, = list(word)
print result,
#output- m
  • Inverting a dictionary You can invert a dictionary where values are unique –
d = {'a':'b','x':'y'}
dict([(v,k) for k, v in d.iteritems()])
#output- {'y': 'x', 'b': 'a'}
  • Cool Printing #1
print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|'
#output- | hej | hej | hej |
  • Cool Printing #2
print 'hej'.center(20, '+')
#output- ++++++++hej+++++++++
  • Checking if an object is stringlike Though we can use type() for this, for some reasons, following method is considered better.
l = [1,2]
isinstance(l, basestring)
#output- False

You can also do this:

l = [1,2]
hasattr(l, 'lower')
#output- False
  • Import antigravity
Import antigravity
#output- link to xkcd Cartoon about Python opens
  • Use of _ in IDE: ‘_’ can be used for result of previous expression.
1 + 2
#output- 3
_ + 3
#output- 6

  • In OOP, we can check all the attributes of an instance by using dir function:
class A:
    def printf(self, name):
	self.name = name
	print self.name
a = A()
>>> dir(a)
['__doc__', '__module__', 'printf']
>>> a.__module__

See also:  Resources for Python