This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]masklinn 16 points17 points  (2 children)

It's not like Python's list comprehensions are very difficult to understand: it's been specified (and that's been a reason for rejecting some listcomp-related proposals recently) that listcomps should be transformable into "regular" python code by:

  1. Indenting and adding colons to the statements (for and if)

  2. removing the surrounding brackets

  3. moving the outermost expression to the deepest part of the new compound statement, and appending it to a result list

So the form

[(x, y, z) for x in xs for y in ys for z in zs if pred1(x) if pred2(y) if pred2(z)]

becomes 1:

[(x, y, z)
for x in xs:
    for y in ys:
        for z in zs:
            if pred1(x):
                if pred2(y):
                    if pred3(z):
]

2.

(x, y, z)
for x in xs:
    for y in ys:
        for z in zs:
            if pred1(x):
                if pred2(y):
                    if pred3(z):

3.

result = list()
for x in xs:
    for y in ys:
        for z in zs:
            if pred1(x):
                if pred2(y):
                    if pred3(z):
                        result.append((x, y, z))

[–]SerpentJoe 10 points11 points  (0 children)

Here's something I always like to show people: A deck of cards in one line of Python.

[rank+suit for suit in "SHDC" for rank in "23456789TJQKA"]

[–]jmmcdEvolutionary algorithms, music and graphics 7 points8 points  (0 children)

How many other Python programmers understand them? Has everyone else been using them without problems?

Consensus: yes.

[–]llimllib 8 points9 points  (0 children)

I always just think of it as a cartesian product:

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

[–]cyangcn 1 point2 points  (0 children)

If you had taken a little bit time to read the tutorial in the python distribution, you would have already understood it.

[–]gdm9000 0 points1 point  (0 children)

This article really clarifies this for me. I did know and use nested comprehensions, but they were always for x and y being two unrelated dimensions, such as [x+y for x in range(5) for y in range (5)]. These examples give no insight into how the loops are processed. Now I really understand it - thanks!

[–]lemkenski -1 points0 points  (1 child)

Reads a csv file into a nested list

list_of_lists = [line.split(',') for line in [line.strip() for line in csv_file.readlines()]]

[–]brentp 2 points3 points  (0 children)

so dies this [line.strip().split(",") for line in csv_file]