Python Tips & Tricks

Below are some cool tips and tricks for python lovers.

List comprehensions and generator expressions

Instead of building a list with a loop:

  1. b = []
  2. for x in a:
  3. b.append(10 * x)
  4. foo(b)

you can often build it much more concisely with a list comprehension:

  1. foo([10 * x for x in a])

List Comprehensions

Suppose you have a list:

  1. bag = [1, 2, 3, 4, 5]

Now you want to double each element in the list, so that it looks like this:

  1. [2, 4, 6, 8, 10]

Most beginners, coming from traditional languages will do something like this:

  1. bag = [1, 2, 3, 4, 5]

  2. for i in range(len(bag)):

  3. bag[i] = bag[i] * 2

But there’s a better way:

  1. bag = [elem * 2 for elem in bag]

2 thoughts on “Python Tips & Tricks”

Leave a Reply

Your email address will not be published. Required fields are marked *