user452187
user452187

Reputation: 123

Python List Comprehension with two parameters

I dont know how the i and j interact in the following code: If i runs into result 2,3,4,5,6,7,8 but how j runs in this situation.

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

Upvotes: 1

Views: 325

Answers (3)

keepAlive
keepAlive

Reputation: 6665

First, avoiding codegolfing, let us reformulate the code as follows:

noprimes = []
for i in range(2, 8):
    for j in range(i*2, 100, i):
        noprimes += [j]

Note that the variable i is comprised between 2 included and 8 excluded. Which means that if you want to work with 8 as included upper bound, your range function must be rewritten as range(2, 8+1). In what follows, I assume that you do want 7 as included upper bound. Furthermore, note that the invisible default parameter here is the step parameter of 1, meaning that range(2, 8) is implicitly range(2, 8, 1).

Second, let us see what is going on by turning this two-levels loop into multiple decomposed one-level ones.

Starting with i=2 such that

i = 2
for j in range(i*2, 100, i):
    noprimes += [j]

is actually equivalent to

for j in range(2*2, 100, 2):
    noprimes += [j]

Above we make j be comprised between 4 included and 100 excluded (98 included) by step of 2.

Identically, for, say, i=3, we have

for j in range(3*2, 100, 3):
    noprimes += [j]

which makes j be comprised between 6 included and 100 excluded by step of 3. And given that 100 is not an integer multiple of 3, the included upper bound will be 99. (Indeed, since 100%3 is equal to 1).

And so on up to 7 included. Which in this case would lead to

for j in range(14, 100, 7):
    noprimes += [j]

which makes j be comprised between 14 included and 100 excluded by step of 7. And given that, as before in the case of 3, 100 is not an integer multiple of 7, the included upper bound will be 100 - 100%7, i.e. 98.



Additionally, in case you wonder, with blabla = [], about the use of

blabla.append('string stuf')

instead of

blabla  += ['string stuf']

or even

blabla.extend(['string stuf'])

note that in this case these 3 approaches, although not the same things, do the same thing. For details about which one to chose, see

append vs. extend

or

What is the difference between “.append()” and “+=[]”?

Upvotes: 0

A Person
A Person

Reputation: 1112

The code you posted uses List Comprehensions. It's a neater way to write:

noprimes = []
for i in range(2, 8):
    for j in range(i*2, 100, i):
        noprimes.append(j)

Upvotes: 0

gold_cy
gold_cy

Reputation: 14236

It is saying:

for i in range(2, 8):
    for j in range(i*2, 100, i):
        noprimes.append(j)

So first it will loop through every number from 2 - 8. For each of these numbers, j will be equal to a number in (i*2, 100, i); (4, 100, 2) <--- this is just the first iteration. The i signifies the starting range number as well as the step for each loop. Hope that helps.

Upvotes: 2

Related Questions