# question regarding list comprehensions

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 20 17:11:37 CEST 2008

```On Mon, 20 Oct 2008 10:20:03 -0400, Pat wrote:

> Finally, if someone could point me to a good tutorial or explain list
> compressions I would be forever in your debt.

Think of a for-loop:

for x in (1, 2, 3):
x

Creates x=1, then x=2, then x=3. It doesn't do anything with the x's, but
just creates them. Let's turn it into a list comp, and collect the x's:

>>> [x for x in (1, 2, 3)]
[1, 2, 3]

for x in (1, 2, 3):
2*x+1

Creates x=1, then evaluates 2*x+1 = 3. Then it repeats for x=2, then x=3.
Here it is as a list comp:

>>> [2*x+1 for x in (1, 2, 3)]
[3, 5, 7]

for x in (1, 2, 3):
if x != 2:
2*x+1

Here it is as a list comp:

>>> [2*x+1 for x in (1, 2, 3) if x != 2]
[3, 7]

You can use any sort of sequence inside a list comp, not just a tuple.

>>> [c.upper() for c in "abcd"]
['A', 'B', 'C', 'D']

You can nest list comps:

>>> [y+1 for y in [2*x+1 for x in (1, 2, 3)]]
[4, 6, 8]

>>> [(y,x) for (x,y) in [(1,2), (3, 4)]]
[(2, 1), (4, 3)]

and also multiple for-loops:

>>> [(x,c) for x in (1, 2) for c in "abc"]
[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c')]

That last one is close to:

for x in (1, 2):
for c in "abc":
(x, c)

--
Steven

```