If you want the effect of a nested for loop, use:

import itertools
for i, j in itertools.product(range(x), range(y)):
    # Stuff...

If you just want to loop simultaneously, use:

for i, j in zip(range(x), range(y)):
    # Stuff...

Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.

UPDATE

Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))

The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.

UPDATE 2

OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:

def equal_elements(t1, t2):
    return [x for x, y in zip(t1, t2) if x == y]

This will return a list containing only the elements that are the same and in the same position in the lists.

Answer from SethMMorton on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › loops - for i and for j in range(n) explained
r/learnpython on Reddit: Loops - for i and for j in range(n) explained
July 3, 2021 -

I'm a Python beginner and wondering if anyone can explain what the for j in range i line is doing here? In addition, what is the proper name for these i and j expressions?

n=5;
for i in range(n):
    for j in range(i):
        print ('* ', end="")
    print('')
for i in range(n,0,-1):
    for j in range(i):
        print('* ', end="")
    print('')
🌐
freeCodeCamp
freecodecamp.org › news › python-for-loop-for-i-in-range-example
Python For Loop - For i in Range Example
March 30, 2021 - In this article, we will look at a couple of examples using for loops with Python's range() function. for loops repeat a portion of code for a set of values. As discussed in Python's documentation, for loops work slightly differently than they do in languages such as JavaScript or C.
Discussions

for loop - python newbie: for j in range - Stack Overflow
That's baggage. So, the better way would be just to use for x in range(10): and just not bother doing print(x); the value is there to make our loop work, not because it's actually useful in any other way. This is the same for j (though I've used x in my examples because I think you're more ... More on stackoverflow.com
🌐 stackoverflow.com
arrays - Using multiple variables in a for loop in Python - Stack Overflow
I wonder if the range concern is still valid since python3 (using iterators and stuff). 2019-10-16T08:14:26.283Z+00:00 ... Yes, it's still valid all the same. 2019-10-16T14:55:50.203Z+00:00 ... Save this answer. ... Show activity on this post. Your third loop will not work as it will throw a TypeError for an int not being iterable. This is because you are trying to "unpack" the int that is the array's index into i, and j ... More on stackoverflow.com
🌐 stackoverflow.com
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
Hi, Usually in Python we can avoid the i = 0 … i += 1 paradigm that we use in other languages when we need to count things, thanks to enumerate(...), for i in range(100), etc. Along the years I have nearly always found a more “pythonic” replacement for code containing i = 0 … i += 1. ... More on discuss.python.org
🌐 discuss.python.org
4
August 10, 2022
python for i in range(5, 0, -1): for j in range(1, i + 1): print(j, end="") print()
The outer loop runs from 5 down to 1 (inclusive), decrementing by 1 each time. The inner loop runs from 1 up to the current value of the outer loop variable i. For each iteration of the inner loop, it prints the current number j without moving to a new line (because of end=""). More on askfilo.com
🌐 askfilo.com
1
December 22, 2025
Top answer
1 of 8
263

If you want the effect of a nested for loop, use:

import itertools
for i, j in itertools.product(range(x), range(y)):
    # Stuff...

If you just want to loop simultaneously, use:

for i, j in zip(range(x), range(y)):
    # Stuff...

Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.

UPDATE

Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))

The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.

UPDATE 2

OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:

def equal_elements(t1, t2):
    return [x for x, y in zip(t1, t2) if x == y]

This will return a list containing only the elements that are the same and in the same position in the lists.

2 of 8
104

There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.

Fortunately, there's simple answers to both. First case, you want to use zip.

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))

will output

1 / 4
2 / 5
3 / 6

Remember that you can put any iterable in zip, so you could just as easily write your exmple like:

for i, j in zip(range(x), range(y)):
    # do work here.

Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.

In the other case, you just want a nested loop.

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))

gives you

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...

You can also do this as a list comprehension.

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]
🌐
DataCamp
datacamp.com › tutorial › python-for-i-in-range
A Beginner's Guide to Python for Loops: Mastering for i in range | DataCamp
January 31, 2024 - The output will be a series of pairs representing all combinations of i and j in the range 0 to 2.
Top answer
1 of 2
1

I think @csevier added a reasonable discussion about your first question, but I'm not sure the second question is answered as clearly for you based on your comments so I'm going to try a different angle.

Let's say you did:

for x in range(10):
    print(x)

That's reasonably understandable - you created a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and you printed each of the values in that list in-turn. Now let's say that we wanted to just print "hello" 10 times; well we could modify our existing code very simply:

for x in range(10):
    print(x)
    print('hello')

Umm, but now the x is messing up our output. There isn't a:

do this 10 times:
    print('hello')

syntax. We could use a while loop but that means defining an extra counter:

loop_count = 0
while loop_count < 10:
    print('hello')
    loop_count += 1 

That's baggage. So, the better way would be just to use for x in range(10): and just not bother doing print(x); the value is there to make our loop work, not because it's actually useful in any other way. This is the same for j (though I've used x in my examples because I think you're more likely to encounter it in tutorials, but you could use almost any name you want). Also, while loops are generally used for loops that can run indefinitely, not for iterating over an object with fixed size: see here.

2 of 2
0

Welcome to the python community! This is a great question. In python, as in other languages, there are many ways to do things. But when you follow a convention that the python community does, that is often referred to as a "pythonic" solution. The method print_progression is a common pythonic solution to iteration of a user defined data structure. In the case above, lets explain first how the code works and then why we would do it that way.

Your print_progression method takes advantage of the fact that your Progression class implements the iteration protocol by implementing the next and iter dunder/magic methods. Because those are implemented you can iterate your class instance both internally as next(self) has done, and externally next(Progression()) which is the exactly what you were getting at with you number 1. Because this protocol is implemented already, this class can by used in any builtin iterator and generator context for any client! Thats a polymorphic solution. Its just used internally as well because you don't need to do it in 2 different ways.

Now for the unused J variable. They are just using that so they can use the for loop. Just using range(n) would just return an itterable but not iterate over it. I dont quite agree with the authors use of the variable named J, its often more common to denote an unused variable that is just used because it needs to be as a single underscore. I like this a little better:

 print(' '.join(str(next(self)) for _ in range(n)))
🌐
Note.nkmk.me
note.nkmk.me › home › python
Python for Loop (With range, enumerate, zip) | note.nkmk.me
August 18, 2023 - In Python, nested loops are created by adding more indentation levels to represent nested code blocks. l1 = [1, 2, 3] l2 = [10, 20, 30] for i in l1: for j in l2: print(i, j) # 1 10 # 1 20 # 1 30 # 2 10 # 2 20 # 2 30 # 3 10 # 3 20 # 3 30
🌐
Python Guides
pythonguides.com › for-i-in-range-python
Understand for i in range Loop in Python
October 7, 2025 - In Python 3, range() returns a range object, which is a sequence type that generates numbers on demand rather than storing the entire sequence in memory. This makes it memory-efficient for large ranges. For example, this won’t consume gigabytes of memory: for i in range(1000000000): if i > 10: # Just process the first few elements break print(i)
Find elsewhere
🌐
Fonzi AI
fonzi.ai › blog › python-for-i-in-range
How to Use "for i in range()" in Python (With Clear Examples)
August 14, 2025 - The for i in range loop is your go-to method for iterating efficiently and cleanly. Python’s built-in range() function provides a versatile way to generate sequences of numbers, enabling you to control the start, stop, and step size of your loops.
🌐
Finxter
blog.finxter.com › home › learn python blog › for loop with two variables (for i j in python)
For Loop with Two Variables (for i j in python) - Be on the Right Side of Change
July 31, 2022 - The Python for loop is a powerful method to iterate over multiple iterables at once, usually with the help of the zip() or enumerate() functions. for i, j in zip(range(10), range(10)): # (0,0), (1,1), ..., (9,9)
🌐
Python Examples
pythonexamples.org › python-for-i-in-range
Python for i in range() - Python Examples
Python for i in range statement is for loop iterating for each element in the given range. In this tutorial, we have examples: for i in range(x), for i in range(x, y), for i in range(x, y, step)
🌐
Medium
medium.com › @toptalenticalcio › understanding-for-i-in-range-python-loops-fa07983469ac
Understanding for i in range Python Loops | by Stefano Cappellini | Medium
February 1, 2024 - In this section, we will explore the syntax and proper usage of the ‘for i in range’ loop in Python. The ‘for i in range’ loop is an essential construct that allows us to iterate over a sequence of values and execute code repeatedly.
🌐
Bookdown
bookdown.org › tpemartin › bookdown-programming-for-math-economics › pythoniterations.html
Chapter 4 Python迴圈 | 經濟數學程式設計專題
import requests response=requests.get("https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=3") danceInfo=response.json() 找出每個danceInfo[i]下的showInfo有多少場訊息,並加總計算所有dance的全部場次數。 · for loop的iterator會儲存最後一個iterate值,要小心後面有用到同樣的iterator變數名稱: · listA=[[1,3,5],[2,4,6]] sum=0 for i in range(len(listA)): for j in range(len(listA[i])): sum +=listA[i][j] print(sum) listA=[[1,3,5],[2,4,6]] sum=0 for i in range(len(listA)): for i in range(len(listA[i])): sum +=listA[i][i] print(sum) 多層迴圈建議以數學下標習慣i, j, k, …,才不會有上述錯誤。 ·
Top answer
1 of 6
36

The simplest and best way is the second one, not the first one!

for i in array:
    do_something(i)

Never iterate indices just to index the container, it's needlessly complicating the code:

for i in range(len(array)):
    do_something(array[i])

If you need the index for some reason (usually you don't), then do this instead:

for i, element in enumerate(array):
    print("working with index", i)
    do_something(element)

This is just an error, you will get TypeError: 'int' object is not iterable when trying to unpack one integer into two names:

for i, j in range(len(array)):
    ...

This one might work, assumes the array is "two-dimensional":

for i, j in array:
    ...

An example of a two-dimensional array is a list of pairs:

>>> for i, j in [(0, 1), ('a', 'b')]:
...     print(f"{i=} {j=}")
...     
i=0 j=1
i='a' j='b'

Note: ['these', 'structures'] are called lists in Python, not arrays.

2 of 6
8

Your third loop will not work as it will throw a TypeError for an int not being iterable. This is because you are trying to "unpack" the int that is the array's index into i, and j which is not possible. An example of unpacking is like so:

tup = (1,2)
a,b = tup

where you assign a to be the first value in the tuple and b to be the second. This is also useful when you may have a function return a tuple of values and you want to unpack them immediately when calling the function. Like,

train_X, train_Y, validate_X, validate_Y = make_data(data)

More common loop cases that I believe you are referring to is how to iterate over an arrays items and it's index.

for i, e in enumerate(array):
    ...

and

for k,v in d.items():  
    ...

when iterating over the items in a dictionary. Furthermore, if you have two lists, l1 and l2 you can iterate over both of the contents like so

for e1, e2 in zip(l1,l2):
    ...

Note that this will truncate the longer list in the case of unequal lengths while iterating. Or say that you have a lists of lists where the outer lists are of length m and the inner of length n and you would rather iterate over the elements in the inner lits grouped together by index. This is effectively iterating over the transpose of the matrix, you can use zip to perform this operation as well.

for inner_joined in zip(*matrix):  # will run m times
    # len(inner_joined) == m
    ...
🌐
Snakify
snakify.org › for loop with range
For loop with range - Learn Python 3 - Snakify
For instance, any string in Python is a sequence of its characters, so we can iterate over them using for: ... Another use case for a for-loop is to iterate some integer variable in increasing or decreasing order. Such a sequence of integer can be created using the function range(min_value, max_value):
🌐
Quora
quora.com › What-does-for-I-in-range-mean-in-Python-and-in-easy-to-understand-language-I-am-just-starting-to-learn
What does 'for I in range()' mean in Python, and in easy to understand language (I am just starting to learn)? - Quora
Answer (1 of 5): Range(…) is a function which generates a sequence of numbers for example : range(1,10) will generate the sequence 1,2,3,4,5.6,7,8,9 (note that the last value is never included). a ‘for loop’ takes a sequence (such as generated by range(…) ),and places a value from the ...
🌐
Quora
quora.com › When-writing-for-I-in-range-the-I-means-what-in-Python
When writing 'for I in range' the I means what in Python? - Quora
Answer (1 of 5): Simplest answer to your question is that ‘I’ is just a variable we are assigning to the values that are iterating in the range of for loop. It is not at all necessary to use ‘I’, we can use other variables as well like [code]for j in range(): ... for k in range(): ... ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-range-function
Python range() function - GeeksforGeeks
It generates numbers dynamically instead of storing them all in memory.. To access elements like a list, convert it using list(range(...)). Example: This example shows the use of range() to generate numbers starting from 0 up to (but not including) ...
Published   March 10, 2026
🌐
Python.org
discuss.python.org › ideas
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
August 10, 2022 - Hi, Usually in Python we can avoid the i = 0 … i += 1 paradigm that we use in other languages when we need to count things, thanks to enumerate(...), for i in range(100), etc. Along the years I have nearly always found a more “pythonic” ...
🌐
Filo
askfilo.com › cbse › smart solutions › for i in range(5, 0, -1): for j in range(1, i + 1): print(j, e
python for i in range(5, 0, -1): for j in range(1, i + 1): ... | Filo
December 22, 2025 - Finally, i = 1. The inner loop runs from j = 1 to j = 1. Output: 1 · The output of the code is: 12345 1234 123 12 1 · Ask your next question · Add an Image · Add a Document · Get solution · Found 7 tutors discussing this question · Monika Discussed · ```python for i in range(5, 0, -1): for j in range(1, i + 1): print(j, end="") print() ``` 9 mins ago ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-loops
Python For Loops - GeeksforGeeks
Python for loops are used to iterate over sequences such as lists, tuples, strings and ranges. Allows the same operation to be applied to every item in a sequence.
Published   May 8, 2026