The current answers are good, but do not talk about how they are just syntactic sugar to some pattern that we are so used to.

Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.

>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]

For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and pythonic:

Approach 1

result = []
for index in range(len(numbers)):
    if numbers[index] > 5:
        result.append(numbers[index])
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 2 (Slightly cleaner, for-in loops)

result = []
for number in numbers:
    if number > 5:
        result.append(number)
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 3 (Enter List Comprehension)

result = [number for number in numbers if number > 5]

or more generally:

[function(number) for number in numbers if condition(number)]

where:

  • function(x) takes an x and transforms it into something useful (like for instance: x*x)
  • if condition(x) returns any False-y value (False, None, empty string, empty list, etc ..) then the current iteration will be skipped (think continue). If the function return a non-False-y value then the current value makes it to the final resultant array (and goes through the transformation step above).

To understand the syntax in a slightly different manner, look at the Bonus section below.

For further information, follow the tutorial all other answers have linked: List Comprehension


Bonus

(Slightly un-pythonic, but putting it here for sake of completeness)

The example above can be written as:

result = filter(lambda x: x > 5, numbers)

The general expression above can be written as:

result = map(function, filter(condition, numbers)) #result is a list in Py2
Answer from UltraInstinct on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_for_loops.asp
Python For Loops
Python Examples Python Compiler ... Q&A Python Bootcamp Python Certificate Python Training ... A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string)....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-for-loops
Python For Loops - GeeksforGeeks
Python for loops are used for iterating over sequences like lists, tuples, strings and ranges. A for loop allows you to apply the same operation to every item within the loop. Using a for loop avoids the need to manually manage the index.
Published ย  3 days ago
Discussions

Python for-in loop preceded by a variable - Stack Overflow
I saw some code like: foo = [x for x in bar if x.occupants > 1] What does this mean, and how does it work? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Need help understanding this while loop
Iโ€™m new to while loops, and I donโ€™t quite get whatโ€™s going on in this code from my book: current_number = 1 while current_number More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
February 13, 2024
Confused about for loops in Python. Please help me break down this code.
You're right, for loops will iterate over something. It turns out that a string is one of those things. It is after all a "string" of letters. So when a string acts as an iterator, you can think of it as being a list of single characters which you loop over one at a time. More on reddit.com
๐ŸŒ r/learnpython
26
26
December 19, 2024
python - "for loop" with two variables? - Stack Overflow
That would certainly be more ... But for just 2 of themโ€ฆ it's hard to beat 2 nested loops for simplicity. 2013-09-06T02:03:05.567Z+00:00 ... And who doesn't love going through indenting everything to make python happy?... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ ForLoop
ForLoop
It is not: it is a Python built-in function that returns a sequence following a specific pattern (most often sequential integers), which thus meets the requirement of providing a sequence for the for statement to iterate over. Since for can operate directly on sequences, there is often no need to count. This is a common beginner construct (if they are coming from another language with different loop syntax):
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_loop.asp
Python - Loop Lists
Learn more about while loops in our Python While Loops Chapter. List Comprehension offers the shortest syntax for looping through lists:
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_for_loops.htm
Python - For Loops
The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence.
๐ŸŒ
IONOS
ionos.com โ€บ digital guide โ€บ websites โ€บ web development โ€บ python for loop
How to use for loops in Python - IONOS
September 30, 2022 - This is also referred to as โ€œiterationโ€. Loops make it possible to repeat a process for several elements of a sequence. For loops are used in Python when the size of a sequence can be determined at program runtime.
Find elsewhere
๐ŸŒ
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu โ€บ notebooks โ€บ chapter05.01-For-Loops.html
For-Loops โ€” Python Numerical Methods
A for-loop assigns the looping variable to the first element of the sequence. It executes everything in the code block. Then it assigns the looping variable to the next element of the sequence and executes the code block again.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ loops-in-python
Loops in Python - GeeksforGeeks
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions).
Published ย  1 month ago
Top answer
1 of 5
131

The current answers are good, but do not talk about how they are just syntactic sugar to some pattern that we are so used to.

Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.

>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]

For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and pythonic:

Approach 1

result = []
for index in range(len(numbers)):
    if numbers[index] > 5:
        result.append(numbers[index])
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 2 (Slightly cleaner, for-in loops)

result = []
for number in numbers:
    if number > 5:
        result.append(number)
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 3 (Enter List Comprehension)

result = [number for number in numbers if number > 5]

or more generally:

[function(number) for number in numbers if condition(number)]

where:

  • function(x) takes an x and transforms it into something useful (like for instance: x*x)
  • if condition(x) returns any False-y value (False, None, empty string, empty list, etc ..) then the current iteration will be skipped (think continue). If the function return a non-False-y value then the current value makes it to the final resultant array (and goes through the transformation step above).

To understand the syntax in a slightly different manner, look at the Bonus section below.

For further information, follow the tutorial all other answers have linked: List Comprehension


Bonus

(Slightly un-pythonic, but putting it here for sake of completeness)

The example above can be written as:

result = filter(lambda x: x > 5, numbers)

The general expression above can be written as:

result = map(function, filter(condition, numbers)) #result is a list in Py2
2 of 5
27

It's a list comprehension

foo will be a filtered list of bar containing the objects with the attribute occupants > 1

bar can be a list, set, dict or any other iterable

Here is an example to clarify

>>> class Bar(object):
...   def __init__(self, occupants):
...     self.occupants = occupants
... 
>>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
>>> foo = [x for x in bar if x.occupants > 1]
>>> foo
[<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]

So foo has 2 Bar objects, but how do we check which ones they are? Lets add a __repr__ method to Bar so it is more informative

>>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
>>> foo
[Bar(occupants=2), Bar(occupants=3)]
๐ŸŒ
ScholarHat
scholarhat.com โ€บ home
Loops in Python - For, While loop (With Examples)
September 10, 2025 - This makes it very useful when you already know how many times you want to loop. ... for letter in 'Python': # First Example print ('Current Letter :', letter) fruits = ['guava', 'apple', 'mango'] for fruit in fruits: # Second Example print ('Current fruit :', fruit) print ("Good bye!")
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Need help understanding this while loop - Python Help - Discussions on Python.org
February 13, 2024 - Iโ€™m new to while loops, and I donโ€™t quite get whatโ€™s going on in this code from my book: current_number = 1 while current_number <= 5: print(current_number) current_number += 1 After just watching a video on Yoโ€ฆ
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ python-for-loop-tutorial
Python for Loop: A Beginner's Tutorial โ€“ Dataquest
March 10, 2025 - In most data science tasks, Python for loops let you "loop through" an iterable object (such as a list, tuple, or set), processing one item at a time. During each iteration (i.e., each pass of the loop), Python updates an iteration variable ...
๐ŸŒ
Real Python
realpython.com โ€บ python-for-loop
Python for Loops: The Pythonic Way โ€“ Real Python
3 weeks ago - This type of loop lets you traverse ... the input collection. In Python, for loops are compound statements with a header and a code block that runs a predefined number of times....
๐ŸŒ
Imperialcollegelondon
imperialcollegelondon.github.io โ€บ python-novice-mix โ€บ 07-for-loops โ€บ index.html
Programming in Python: For Loops
November 8, 2018 - Doing calculations on the values in a list one by one is as painful as working with pressure_001, pressure_002, etc. A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ confused about for loops in python. please help me break down this code.
r/learnpython on Reddit: Confused about for loops in Python. Please help me break down this code.
December 19, 2024 -

I am an absolute beginner in programming, so please forgive my utter lack of understanding.

I came across this concept quite recently through a course I am taking in Python. I re-watched the lessons, I have tried doing some separate research on this topic, but I am still having a hard time wrapping my head around it.

The project I am currently working on is a random password generator. I was stumped and couldn't figure it out on my own so I watched the teacher's solution as a last resort. Especially puzzled when she used this code:

password = ""
for char in password_list:
    password += char

For context, this code is supposed to convert a list of characters (from password_list) into a string.

I thought that for loops were used for iteration. I am only familiar with using "for __ in __ range(a, b)" so far, so I was quite puzzled by this loop as I don't understand how it works. Could someone please help me break it down into simpler terms? That would be super appreciated.

Please and thank you.

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)]
๐ŸŒ
GitConnected
levelup.gitconnected.com โ€บ 5-machine-learning-failures-that-taught-me-more-than-any-course-80f4a2784405
5 Machine Learning Failures That Taught Me More Than Any Course | by Maria Ali | Feb, 2026 | Level Up Coding
2 weeks ago - 5 Machine Learning Failures That Taught Me More Than Any Course Infinite Loop Gone Wrong I still remember the day I confidently deployed my first ML project. I had spent three sleepless nights โ€ฆ
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ for-loop
Python For Loop: Syntax and Examples [Python Tutorial]
Start your coding journey with Python. Learn basics, data types, control flow, and more ... item: The loop variable that takes the current item's value in the sequence during each iteration of the loop. in: The keyword that links the variable to the sequence. sequence: The array, tuple, dictionary, set, string, or other iterable data types to iterate over. Using indentation, the block of code after the for loop statement executes as long as there are items in the sequence.
๐ŸŒ
IBM
ibm.com โ€บ reference โ€บ python โ€บ for-loop
What is a for loop in python? | IBM
November 21, 2025 - This construct allows you to perform tasks such as iterating over a list, array or collection until the end of the sequence is reached, or performing a certain action a set number of times. In essence, a for loop is designed to move to the next element in the sequence after each iteration, ensuring that each item is processed. In Python, the for loop is a versatile tool.