loremIpsum1771 loremIpsum1771 - 1 year ago 104
Python Question

Functionality of list comprehension with two for loops

I was reading through an article explaining list comprehensions and came across the following example which is supposed to build a list of non-prime numbers:

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

I tried breaking the list comprehension down by running both for loops separately in a shell, but I'm still unclear as to the functionality of the statement. It seems that the first loop is supposed to be iterating through the list of numbers from 2 to 8 and then storing each number in j which is then passed to the second (nested?) loop which generates numbers from the current value of i times 2 until 50 in increments of i.

What I've described the actual functionality of the list comprehension?

Answer Source

This list comprehension performs the same as the following code:

noprimes = []
for i in range(2,8):
    for j in range(i*2, 50, i):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download