Steven D'Aprano wrote:
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]


Advanced: you can use tuple-unpacking:

[(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)



Thank you. I think that clears up the mystery a bit. I added your note to my snippets file. When I have a situation that I can't resolve, I'll ask with the specifics.

I really do try to learn this as much as possible on my own without just flinging a question onto the forum.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to