The ConfusionScenario: You were asked to write the equivalent list comprehension of the following code:
Before, starting with the above one we try the simplest one:
for i in range(6): for j in range(i): j
t =  for i in range(6): t.append(i**2)We already know the syntax of list comprehension is as follows:
expression for expr in sequence1So, for the above code we write:
[i**2 for i in range(6)]You might have already started to smell the confusion, didn’t you? If not Read on… 🙂 Now, if I ask you to write the list comprehension for the first example code, you might end up with the following:
when you execute the above code: Surprise, surprise! You will get a NameError instead!
[ j for j in range(i) for i in range(6)]
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'i' is not defined
What went wrong?The nested
fors in the list comprehension are evaluated from left to right. So, the correct list comprehension is:
In the official documentation they explained it thoroughly!
[j for i in range(6) for j in range(i)]
List comprehensions have the form:
[ expression for expr in sequence1 for expr2 in sequence2 ... for exprN in sequenceN if condition ]
for…inclauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are not iterated over in parallel, but from left to right; this is explained more clearly in the following paragraphs. The elements of the generated list will be the successive values of expression. The final if clause is optional; if present, expression is only evaluated and added to the result if condition is true. To make the semantics very clear, a list comprehension is equivalent to the following Python code:
for expr1 in sequence1: for expr2 in sequence2: ... for exprN in sequenceN: if (condition): # Append the value of # the expression to the # resulting list.