-2

In Python 3.x when we execute:

for i in range(2):
    for j in range(2):
        print (i,j)

We get:
0 0
0 1
1 0
1 1

Is there any way I can create 2 for loops where my range of i is (0,5) and range of j is (10,15)? Maybe like:

for i,j in range("myrange for i and myrange for j"):
print(i,j)

And the output would be:
0 10
1 11
2 12
3 13 and so on.

Hello.World
  • 720
  • 8
  • 22
  • @miradulo The nominated duplicate is wrong, the OP needs `for i in range(3): j=i+10` and no nested loops at all. (This is probably still a duplicate of an existing question.) – tripleee Apr 15 '18 at 05:14
  • @tripleee Oh...my mistake, didn't even consider that. Thanks. – miradulo Apr 15 '18 at 05:34
  • Why 3 downvotes? – Hello.World Apr 15 '18 at 06:29
  • Probably because this is an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) -- you have one problem and seem to be asking about another which you think is related but isn't. – tripleee Apr 17 '18 at 06:55
  • Maybe the way the asked was wrong which someone could have pointed out. Now I am unable to ask further questions. I don't know how I can reverse this. – Hello.World Apr 17 '18 at 06:59

1 Answers1

4

You are looping over pairs of related values, not over two independent lists. There is no nesting, just a single loop which fetches one pair at a time.

for i in range(5):
    j = i+10
    print(i, j)

In a more general case, if j is not always trivially derivable from i, you could say

for i, j in [(0, 10), (1, 42), (2, 12)]:
    print(i, j)

If i and j are populated from two existing lists of the same length

ilist = [0, 1, 2]
jlist = [10, 42, 12]
for i, j in zip(ilist, jlist):
    print(i, j)

If i is just the index within the j list, you can use enumerate:

for i, j in enumerate(range(10, 14)):
     print(i, j)

If you think of nesting as dimensions, you can argue that there are rows (i values) and columns (j values to add);

for i in range(5):
    result = list()
    for j in (0, 10):
        result.append(i+j)
    print(*result)

So now, each i value gets added to each j value, and you collect and print those sums for each i value. Because the first j value on the first iteration of the inner loop is 0 every time, the first output value is conveniently identical to the input i value.

tripleee
  • 175,061
  • 34
  • 275
  • 318