The Confusion

Scenario: You were asked to write the equivalent list comprehension of the following code:
for i in range(6):
    for j in range(i):
Before, starting with the above one we try the simplest one:
t = []
for i in range(6):
We already know the syntax of list comprehension is as follows: expression for expr in sequence1 So, 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:
[ j for j in range(i) for i in range(6)]
when you execute the above code: Surprise, surprise! You will get a  NameError instead!
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:
[j for i in range(6) for j in range(i)]
In  the official documentation they explained it thoroughly!
List comprehensions have the form:
 [ expression for expr in sequence1
              for expr2 in sequence2 ...
              for exprN in sequenceN
              if condition ]
The for…in clauses 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.

About the Author ওয়াসী (Wasi)

Crawl, Scrape, Extract, Compare and automate scripts for Data Mining & Analysis, Web Scraping, Lead Generation etc. Contact me for more details about my services.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.