Let’s take a look at your understanding of the list, but first we’ll start by understanding the list and the easiest way.
l = [1,2,3,4,5] print [x for x in l]
You can look at this in the same way as you can look at a loop built like this:
for x in l: print x
Now let's look at another:
l = [1,2,3,4,5] a = [x for x in l if x % 2 == 0] print a
This is exactly the same as this:
a = [] l = [1,2,3,4,5] for x in l: if x % 2 == 0: a.append(x) print a
Now consider the examples you provided.
l = [[1,2,3],[4,5,6]] flattened_l = [item for sublist in l for item in sublist] print flattened_l
To understand the list, start from the farthest left for the loop and work your way up. In this case, the variable element will be added. It will produce this equivalent:
l = [[1,2,3],[4,5,6]] flattened_l = [] for sublist in l: for item in sublist: flattened_l.append(item)
Now for the last
exactly_the_same_as_l = [item for item in sublist for sublist in l]
Using the same knowledge, we can create a for loop and see how it looks.
for item in sublist: for sublist in l: exactly_the_same_as_l.append(item)
Now, the only reason this works is because when creating flattened_l she also created a sublist . This is a summary reason why this did not cause an error. If you run this without defining flattened_l, you will get a NameError