0

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)?

2
  • You have two question here, can you please edit it down to one? Thanks Commented Jun 19, 2020 at 0:49
  • Sorry about the two questions in what was supposed to be one question. I thought they were so related that they could be thought of as parts of a question. Someone already answered the question so I won't change it now but I will keep that in mind for the future! Thanks! Commented Jun 19, 2020 at 1:00

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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)):

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.