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.

Answer from wim on Stack Overflow
🌐
Reddit
reddit.com › r/python › for loops with multiple variables
r/Python on Reddit: For loops with multiple variables
May 8, 2019 -

I am learning python and I have seen some pretty funky for loops iterating multi-dimensional arrays and k, v values in dictionaries.

Anyone got a link or explanation to a novice to help understand?

Top answer
1 of 2
3
If you have a list which contains tuples, then you can loop over it normally, extracting the entire tuple. my_list = [(1,2,3), (4,5,6), (7,8,9)] for triple in my_list: print(triple) When your list contains lists or tuples, you can declare multiple variables left of the in operator to unpack that list or tuple. for x, y, z in my_list: print(x, y, z) You can do the same with the zip function to create tuples containing the i'th elements of multiple lists of equal size on the fly. for x, y, z in zip(range(1,4), range(4,7), range(7,10)): print(x, y, z) See more about Unpacking, I recommend Trey Hunner's blog https://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/
2 of 2
1
I like to explain this in terms of a simple analogy. In python for loop is like a special switch to a candy dispenser. You press the switch and the dispenser gives out candies one by one until they run out (or you decide to break because you're getting a sugar high). However the twist is that in the dispenser there give out a single candy or a packet of candy (or packet of candy inside a packet and so on...:)). You can choose to get the whole packet by pressing a button OR if you prefer you can ask the machine to unwrap the packet and dispense individual candies. However you must have that many separate containers to hold the unpacked candies, otherwise the machine will throw an error "No candy for you!". In python world these candy dispensers are called iterators and they can be lists, tuples, strings, dictionaries and so on. There's some subtlety in what each iterator returns in a for loop (for example using only for key in dict returns the key of a dictionary). But the basic principle is the same, if the iterator returns a single value you can bind that to a single variable. If the iterator returns another iterable you can either bind that to a single variable or you can unpack it by using multiple variables. A great advantage of this scheme is that for example in a loop if you want to get both the index as well as element you can use enumerate function which returns a list of tuples containing the element and its index. For example for i, elem in enumerate(somelist): print(i, elem).
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
    ...
Discussions

python - Is there any way to create multiple variables using a for loop? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Creating multiple variables with consecutive names using a for loop
I want to create several variables with consecutive names. For instance, I want to create 100 variables like variable_1, variable_2, … , variable_100, and maybe assign a random vector to each of them, e.g. variable_1 = rand(1,10). Then I want to iterate through each of them and change some ... More on discourse.julialang.org
🌐 discourse.julialang.org
8
1
April 2, 2020
Using a loop to create and assign multiple variables (Python) - Stack Overflow
I'm looking to use a for loop to create multiple variables, named on the iteration (i), and assign each one a unique int. More on stackoverflow.com
🌐 stackoverflow.com
May 26, 2017
python - How do you create different variable names while in a loop? - Stack Overflow
For example purposes... for x in range(0,9): string'x' = "Hello" So I end up with string1, string2, string3... all equaling "Hello" More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › python help
Creating new variables inside a for loop - Python Help - Discussions on Python.org
June 10, 2024 - Hello! I am a relatively new python user with little experience in for loops, and one is definitely necessary for my project. I have a pandas dataframe that looks like this: And I need to “integrate” the accel columns their respective velocity (and eventually position) and the angular into ...
🌐
Delft Stack
delftstack.com › home › howto › python › python for loop multiple variables
How to Use a for Loop for Multiple Variables in Python | Delft Stack
February 9, 2025 - For each iteration, the i variable holds the current index, and item1 and item2 are assigned the elements from list1 and list2 at that index, respectively. Consequently, this method facilitates a pairing of elements, assuming the iterables are of the same length. The code output shows the successful pairing of elements from both list1 and list2. Nested for loops in Python provide a versatile approach to dealing with multiple variables in a structured and organized way.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-for-loop-multiple-variables
Using multiple variables in a For loop in Python | bobbyhadz
Use the zip function to group multiple iterables into tuples. Use a for loop to iterate over the zip object. Unpack the items of each tuple into variables.
🌐
Sololearn
sololearn.com › en › Discuss › 1958256 › what-does-multiple-variables-mean-in-python-for-loop-
What does multiple variables mean in Python 'for loop' ?
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
Find elsewhere
🌐
AskPython
askpython.com › home › for loop with two variables in python
For Loop with Two Variables in Python - AskPython
February 15, 2023 - This is the most basic and easy example to understand how the loop runs through the list of languages. languages = ["C", "Python", "Java", "JavaScript", "Go"] for language in languages: print(language) assigned a list of languages(C, Python, Java, JavaScript, Go) to the variable languages
🌐
YouTube
youtube.com › watch
create multiple variables in for loop python - YouTube
Download this code from https://codegive.com Certainly! In Python, it's possible to create multiple variables within a for loop using iterable unpacking or m...
Published   December 27, 2023
🌐
Quora
quora.com › How-do-I-create-a-loop-that-creates-variables-in-Python
How to create a loop that creates variables in Python - Quora
Answer (1 of 6): You don’t. Now I know someone will come along with a solution involving locals(), but then to use those ‘variables’ in your code you would need use ‘locals()’. Misusing locals() especially writing to it is a sign of a bad design. It is far simpler just to add items ...
🌐
Reddit
reddit.com › r/learnpython › need help printing multiple variables with a loop
r/learnpython on Reddit: Need help printing multiple variables with a loop
January 5, 2023 -

I want to print an undefined amount of variables that are named like this: var_1, var_2, var_3, etc.

I created a for loop which runs a specific amount of times depending on how many variables there are:

count = 1

for i in range(x):

print("var_" + str(count))

count += 1

However this prints the variables by their name and not the integer/string they are defined to earlier. I was hoping someone could tell me if there is a way to fix this, or a better way to do it.

🌐
Imperialcollegelondon
imperialcollegelondon.github.io › python-novice-mix › 07-for-loops › index.html
Programming in Python: For Loops
November 8, 2018 - Update the variable with values from a collection. # Sum the first 10 integers. total = 0 for number in range(10): total = total + (number + 1) print(total) ... Add 1 to the current value of the loop variable number.
🌐
Processing Forum
forum.processing.org › one › topic › create-multiple-variables-using-for-loop.html
Create multiple variables using for loop - Processing Forum
} Where method1(), method2(), method3() and so on, are functions you create inside class Ball to move and animate the object! Also, take a look on a similar example in this link -> Bouncing Balloons ... I've got it working now. Thank you for your comments, they really helped! :) ... {"z23575804":[25080000001841450,25080000001843131],"z20603759":[25080000001839973],"z21661383":[25080000001842483]} ... Code optimization using FOR loops &...
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)]
🌐
W3Schools
w3schools.com › python › python_variables_multiple.asp
Python Variables - Assign Multiple Values
Python Tuples Access Tuples Update Tuples Unpack Tuples Loop Tuples Join Tuples Tuple Methods Tuple Exercises Code Challenge Python Sets
🌐
Reddit
reddit.com › r/learnpython › is it possible to create variables in a loop?
r/learnpython on Reddit: Is it possible to create variables in a loop?
June 10, 2022 -

I need to create a large number of variable. Currently what I have is:

var1 = 0
var2 = 0
...
var1000 = 0

Is it possible to create these variables in some sort of loop instead of writing each one?

#Pseudocode

for i in range(1000):
    var_i = 0

Update:

Thanks a lot for all the comments! The list idea worked!