Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created February 7, 2016 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyhunner/9ed64cecc37ad939e098 to your computer and use it in GitHub Desktop.
Save treyhunner/9ed64cecc37ad939e098 to your computer and use it in GitHub Desktop.
List comprehensions lightning talk code copy-pasting examples

If we have a for loop that converts one list to another list using a transformation for each element:

doubled_numbers = []
for n in numbers:
    doubled_numbers.append(n * 2)

We can make that into a list comprehension by copy-pasting the assignment, the append value, and the for clause:

doubled_numbers = [n * 2 for n in numbers]

If we have a for loop that converts one list to another list conditionally:

doubled_odds = []
for n in numbers:
    if n % 2 == 1:
        doubled_odds.append(n * 2)

We can make that into a list comprehension by copy-pasting the assignment, the append value, the for clause, and the if clause:

doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

If we have a for loop that doesn't convert a list to a list:

sum_of_squares = 0
for n in numbers:
    sum_of_squares += n ** 2

But we can figure out how to covert this to a list to a list transformation:

squares = []
for n in numbers:
    squares.append(n ** 2)

sum_of_squares = sum(squares)

Then we can copy-paste our way into a list comprehension in the same way:

sum_of_squares = sum([n ** 2 for n in numbers])

And in fact we can even remove the brackets and use a generator expression:

sum_of_squares = sum(n ** 2 for n in numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment