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('')
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)]
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
"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
understanding range in python for loop - Stack Overflow
The program below is finding prime numbers in a given range. for the noprimes list comprehension part, why do we have 3 parameters in range? noprimes = [j for i in range(2, 8) for j in range(i*2, ... More on stackoverflow.com
🌐 stackoverflow.com
What does "for i in range" mean in Python?
Use a 'code block' in the 'new' reddit to paste code so we can see indents which are vital to python! for i in range(n + 1): sum = sum + i * i * i when you say 'for i in range(n + 1)' you are creating a variable called 'i' and setting it equal to the first value in the second part of the line called range(). every time the loop loops, i becomes the next value in the second part of the line (in this case range()) Check this code out to understand it: my_list = ['potato', 'pineapple', 'strawberry', 'banana', 'orange'] for var in my_list: #instead of 'i' i used 'var' you can use any name you want, since you are creating the variable. var is = to a value in my_list, and will go to the next value every time the loop loops. This will run a total of 5 times, because there are 5 items in the list we are looping through (my_list) print(var) now put that in your terminal/whatever and see the output, itll look like this: potato pineapple strawberry banana orange its the same with range() -- example: range(5) just means every number between 0 and 5, including 0 but not 5. so range(5) has 5 items, 0, 1, 2, 3 and 4. our loop should run 5 times: for i in range(5): print(i) you should see the output: 0 1 2 3 4 if you ever want to know more about certain parts of python, google it, for example: 'python range()' will give you tons of results that are helpful. More on reddit.com
🌐 r/learnpython
13
17
September 9, 2019
🌐
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.
🌐
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 outer loop (for i in range(3)) iterates through the numbers 0, 1, and 2. For each iteration of the outer loop, the inner loop (for j in range(3)) also iterates through the numbers 0, 1, and 2.
🌐
W3Schools
w3schools.com › python › ref_func_range.asp
Python range() Function
Python Strings Slicing Strings Modify Strings Concatenate Strings Format Strings Escape Characters String Methods String Exercises Code Challenge Python Booleans ... Python Operators Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge Python Lists · Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises Code Challenge Python Tuples
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:

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

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

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

Copydo this 10 times:
    print('hello')

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

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

Copy print(' '.join(str(next(self)) for _ in range(n)))
🌐
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
Originally Answered: When writing "for I in range" the I means what in Python? · · 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.
Find elsewhere
🌐
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):
🌐
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.
🌐
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 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)
🌐
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   1 month ago
🌐
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” replacement for code containing i = 0 … i += 1. There is an exception with this code: an infinite loop with a counter: i = 0 while True: ... if breaking_condition: break i += 1 Proposal: could we accept that range() without any parameter ...
Top answer
1 of 4
17

See the docs:

range([start], stop[, step])

When comparing it to a for(..; ..; ..) loop e.g. in C the three arguments are used like this:

for(int i = start; i != stop; i += step)

There are also good examples in the docs:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
2 of 4
5

For range(), the basic idea is that it generates a sequence of items for you. See this as reference http://docs.python.org/library/functions.html#range :

 format: range([start], stop[, step])

In the meantime here is some basic explanation, easiest example:

 range(5)

will generate numbers in the range starting at 0 (default start value) and go up to but not including 5, by increments of 1 (default value), so

 In [1]: range(5)
 Out[1]: [0, 1, 2, 3, 4]

You can specify additional parameters to range, such as the starting value, the ending value and also the stepvalue. So range(startval, endval, stepval). Notice that endval is not included in the sequence that is generated.

 range(0, 5, 1)

is equivalent to

 range(5)

To generate all even numbers between 0 and 20 you could do for instance

 range(0, 21, 2)

Note that prior to Python 3 range generates a list and xrange generates the number sequence on demand.

In your specific code are using list comprehensions and range. It might be easier to understand the algorithm and the role of the for loops with range by eliminating the list comprehension temporarily to get a clearer idea. List comprehension is a powerful and efficient construct and should definitely be used if you plan on keeping the original code though.

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

# primes = [x for x in range(2, 50) if x not in noprimes]
primes = []
for x in range(2, 50):
   if x not in noprimes:
      primes.append(x)
🌐
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)
🌐
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.
🌐
PYnative
pynative.com › home › python › python range() explained with examples
Python range() Function Explained with Examples
March 17, 2022 - The step value must not be zero. If a step=0, Python will raise a ValueError exception. ... Use range() to generate a sequence of numbers starting from 9 to 100 divisible by 3. ... # start = 9 # stop = 100 # step = 3 (increment) for i in range(9, 100, 3): print(i) Code language: Python (python) Run
🌐
StrataScratch
stratascratch.com › blog › python-for-loop-range-function
How Does Python For Loop Range Function Work? - StrataScratch
November 5, 2025 - for customer_id in range(1, 6): print(f"Sending email to customer #{customer_id}") Here is the output. The loop runs exactly 5 times. customer_id starts at one and stops before 6, giving you IDs 1 through 5. Behind the scenes, Python iterates through a sequence produced by range(), just as it would when you loop through a list in Python or other iterables.
🌐
Reddit
reddit.com › r/learnpython › what does "for i in range" mean in python?
r/learnpython on Reddit: What does "for i in range" mean in Python?
September 9, 2019 -

So, I had a question where I was supposed to find the sum of the first natural numbers using Python.

Here's the problem:

Write a program to find the sum of the cubes of the first n natural numbers, where the value of n is provided by the user.

And this is the code that my professor used to allow the interpreter to produce the result:

= int(input("Enter a number:"))

sum = 0

for i in range (n+1): sum = sum + i*i*i

# for i in range starts as a loop, and then tries to get to (n + 1), whatever that may be

print("the sum of the first", n, "integers is", sum)

However, I can't seem to understand what "for i in range (n + 1): sum = sum + i * i * i" means. In other words, I don't understand what role this part of the code is doing to produce the result. Especially, I don't understand what the role of "for i in range (n + 1)" is doing. Does anyone mind explaining this to me?

Top answer
1 of 6
23
Use a 'code block' in the 'new' reddit to paste code so we can see indents which are vital to python! for i in range(n + 1): sum = sum + i * i * i when you say 'for i in range(n + 1)' you are creating a variable called 'i' and setting it equal to the first value in the second part of the line called range(). every time the loop loops, i becomes the next value in the second part of the line (in this case range()) Check this code out to understand it: my_list = ['potato', 'pineapple', 'strawberry', 'banana', 'orange'] for var in my_list: #instead of 'i' i used 'var' you can use any name you want, since you are creating the variable. var is = to a value in my_list, and will go to the next value every time the loop loops. This will run a total of 5 times, because there are 5 items in the list we are looping through (my_list) print(var) now put that in your terminal/whatever and see the output, itll look like this: potato pineapple strawberry banana orange its the same with range() -- example: range(5) just means every number between 0 and 5, including 0 but not 5. so range(5) has 5 items, 0, 1, 2, 3 and 4. our loop should run 5 times: for i in range(5): print(i) you should see the output: 0 1 2 3 4 if you ever want to know more about certain parts of python, google it, for example: 'python range()' will give you tons of results that are helpful.
2 of 6
2
It means that you're looping through the function body n times. So, for i in range(n) means that you're going to do something n times. For example: for i in range(10): print(n) means you're going to print the numbers 0 to 9, because the range function goes from 0 to n-1 if you provide a single argument, and from a to b if you provide two, as in range(a, b)
🌐
Rose-Hulman Institute of Technology
rose-hulman.edu › class › cs › csse120 › VideoFiles › 08.1-RangeExpressions › RangeExpressions.pdf pdf
Python’s range expression Recall that a range expression
Caution: range(m, n) generates NO integers if n  m. For · example, the loop for k in range(9, 5): runs NO times: The third form of the range expression works like this: For example, the loops below generate the output shown to the right. Caution: In all three forms, the generated numbers start at the · first number and stop just ...