theMobDog theMobDog - 1 year ago 78
Python Question

python: nested unwrapping in list-comprehension

I am trying to achieve this in list comprehension

for y in range(depth): # this one works
mylist+=[x for x in s[y]]

This needs help:

# s= [set() for _ in range(depth)] # or list of sets
mylist=[x for x in s[y] for y in range(depth)]
SyntaxError: invalid syntax

Is it possible to achieve this in list-comprehension?

Main question ends here.

More on the errors,

Instead of syntax error, I also get
name y not defined

So I tried
before the list-comprehension. And it worked! No more name error. Except, it wasn't printing out the content of the list, but rather some loopy numbers.

Even tho, what I am trying to do is violating something, python also seems to be acting strangely. Probably a bug.

Answer Source

You are looking for the following:

mylist.extend([x for y in range(depth) for x in s[y]])

The levels of a comprehension should be placed in the same order as the loop. Doing otherwise was causing the interpreter to see for x in s[y] before it produced a y from for y in range(depth).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download