{{ message }}

Instantly share code, notes, and snippets.

# treyhunner/doubled_numbers.md

Created Feb 7, 2016
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)`