Reputation: 27
I was toying around with Python and I ran the following:
for i,j in (range(-1, 2, 2),range(-1, 2, 2)):
print(i,j)
I expected this to print
>> -1, -1
>> 1, 1
However what came out was
>> -1, 1
>> -1, 1
(1) Why is this the output and what is going on behind the scenes
(2) If I wanted to get all combinations of -1 and 1 (which are(-1,-1), (-1,1), (1,-1), and (1,1)) I know that I can use a nested for loop
for i in range(-1,2,2):
for j in range(-1,2,2):
print(i,j)
However is there a way to do this in one line with one for loop call (what I was trying to do with the original code)?
Upvotes: 0
Views: 77
Reputation: 13057
You can think range(-1, 2, 2) is (-1, 1), then
for i, j in (range(-1, 2, 2), range(-1, 2, 2)):
is similar
for i, j in ((-1, 1), (-1, 1)):
You should do it like this
for i, j in zip(range(-1, 2, 2), range(-1, 2, 2)):
print(i, j)
To all combinations of -1 and 1, use this is more flexiable
for i in range(-1,2,2):
for j in range(-1,2,2):
print(i,j)
or this
from itertools import product
for i, j in product(range(-1, 2, 2), range(-1, 2, 2)):
Upvotes: 1
Reputation: 161
First question : You are iterating over i and j over a tuple (range(-1, 2, 2), range(-1, 2, 2)). try this code and you'll understand.
>>> for i in (range(-1, 2, 2),range(-1, 2, 3)):
... print(i)
...
range(-1, 2, 2)
range(-1, 2, 3)
Upvotes: 2
Reputation: 2882
For your first question, in the first iteration loop it takes range(-1, 2, 2)
which expands to [-1, 1]
and then assigns i=-1
and j=1
. Similarly in the second cycle it does the same for the second range(-1, 2, 2)
. You're lucky that you have two elements in that range. Otherwise it would raise error, e.g., range(-1, 4, 2)
would raise error as it has 3 elements. You need to use i, j, k for that loop.
For your second question use itertools.product
.
for i in product(range(-1, 2, 2), range(-1, 2, 2)):
print(i)
#(-1, -1)
#(-1, 1)
#(1, -1)
#(1, 1)
Upvotes: 2