Here are some cool tricks to write better python code:
List comprehensions:
Instead of building a list with a loop:
1 2 3 4 |
b = [] for x in a: b.append(10 * x) foo(b) |
We can often build it much more concisely with a list comprehension:
1 |
b = [10 * x for x in a] |
Enumerate
We can use enumerate to do a for loop:
1 2 3 4 |
i = 0 for item in iterable: print i, item i += 1 |
like this:
1 2 |
for i, item in enumerate(iterable): print i, item |
Enumerate can also take a second argument. Here is an example:
1 2 3 4 5 |
>>> list(enumerate('abc')) [(0, 'a'), (1, 'b'), (2, 'c')] >>> list(enumerate('abc', 1)) [(1, 'a'), (2, 'b'), (3, 'c')] |
Dict/Set comprehensions
dict/set comprehensions are simple to use and just as effective:
1 2 3 4 |
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 |
[Read More...]