0

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?

loremIpsum1771
  • 2,277
  • 3
  • 29
  • 68

1 Answers1

2

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):
        noprimes.append(j)
mtadd
  • 2,315
  • 13
  • 18