This doesn't have anything to do with for loops or the variables they use. = is always a reassignment. i = whatever we changes what i points to. It never ever changes any other references that might also have pointed to the same object. If you don't understand that, read this: https://nedbatchelder.com/text/names.html Answer from danielroseman on reddit.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_for_loops.asp
Python For Loops
Remove List Duplicates Reverse ... 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)....
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ ForLoop
ForLoop - Python Wiki
Contrast the for statement with the ''while'' loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example: For loop from 0 to 2, therefore running 3 times. for x in range(0, 3): print("We're on time %d" % (x))
Discussions

What exactly is i in a for loop?
This doesn't have anything to do with for loops or the variables they use. = is always a reassignment. i = whatever we changes what i points to. It never ever changes any other references that might also have pointed to the same object. If you don't understand that, read this: https://nedbatchelder.com/text/names.html More on reddit.com
๐ŸŒ r/learnpython
41
27
December 10, 2024
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
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
Can not understand for loops
You're following a recipe for potato soup. It says "wash and peel five potatoes." But you only know how to wash and peel one potato. So you wash and peel one potato, then another, then another, until you've done it to five potatoes. That's a for loop: "for each of five potatoes, wash the potato, then peel it." More on reddit.com
๐ŸŒ r/learnpython
90
262
August 14, 2021
๐ŸŒ
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 weeks ago
๐ŸŒ
Real Python
realpython.com โ€บ python-for-loop
Python for Loops: The Pythonic Way โ€“ Real Python
February 23, 2026 - Pythonโ€™s for loop iterates over items in a data collection, allowing you to execute code for each item. To iterate from 0 to 10, you use the for index in range(11): construct. To repeat code a number of times without processing the data of ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ loops-in-python
Loops in Python - GeeksforGeeks
For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a block of code repeatedly, once for each item in the sequence. ... Explanation: This code prints the numbers from 0 to 3 (inclusive) using ...
Published ย  5 days ago
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ for-loop
Python for Loop (With Examples)
Here, when lang is equal to 'Go', the break statement inside the if condition executes which terminates the loop immediately. This is why Go and C++ are not printed. The continue statement skips the current iteration of the loop and continues with the next iteration. For example, languages = ['Swift', 'Python', 'Go', 'C++'] for lang in languages: if lang == 'Go': continue print(lang)
๐ŸŒ
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.
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what exactly is i in a for loop?
r/learnpython on Reddit: What exactly is i in a for loop?
December 10, 2024 -

I was working on a beginner's python exercise that involved writing a function that takes a list of floating numbers and returns the same list as strings displayed to 2 decimal places. This was what I initially wrote:

def formatted(a_list):
    for i in a_list:
        i = f"{i:.2f}"
    return a_list

print(i) after i = f"{i:.2f}" showed correct values, but the returning a_list remained unedited. It seems to me that i does not represent the actual items within a_list, but behaves more so like a copied value?

I solved the problem by .append()-ing the formatted items to a new list but my lack of genuine understanding bugs me.

What's happening under the hood? What exactly is i in a for loop? Thanks!

๐ŸŒ
Imperialcollegelondon
imperialcollegelondon.github.io โ€บ python-novice-mix โ€บ 07-for-loops โ€บ index.html
Programming in Python: For Loops
November 8, 2018 - Write for loops that use the ... 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....
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_loop.asp
Python - Loop Lists
A short hand for loop that will print all items in a list: thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist] Try it Yourself ยป ยท Learn more about list comprehension in the next chapter: List Comprehension. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
Learn Python
learnpython.org โ€บ en โ€บ Loops
Loops - Learn Python - Free Interactive Python Tutorial
primes = [2, 3, 5, 7] for prime in primes: print(prime) For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange).
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ controlflow.html
4. More Control Flow Tools โ€” Python 3.14.3 documentation
Later we will see more functions that return iterables and take iterables as arguments. In chapter Data Structures, we will discuss list() in more detail. The break statement breaks out of the innermost enclosing for or while loop: >>> for n in range(2, 10): ...
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)]
๐ŸŒ
Data Science Discovery
discovery.cs.illinois.edu โ€บ learn โ€บ Simulation-and-Distributions โ€บ For-Loops-in-Python
For-Loops in Python - Data Science Discovery
# Notice the variable `suit` and the list of all suits:\nfor suit in ["Club", "Heart", "Diamond", "Spade"]:\n print(suit) ... Using a for-loop to visit every element in a Python List.
๐ŸŒ
Python Course
python-course.eu โ€บ python-tutorial โ€บ for-loops.php
20. For Loops | Python Tutorial | python-course.eu
The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks like this: for <variable> in <sequence>: <statements> else: <statements>
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-for-loop-example
Python for loop | DigitalOcean
March 14, 2024 - In this article, weโ€™ll explore the Python for loop in detail and learn to iterate over different sequences including lists, tuples, and more. Additionally, weโ€™ll learn to control the flow of the loop using the break and continue statements. Anytime you have need to repeat a block of code ...
๐ŸŒ
Snakify
snakify.org โ€บ for loop with range
For loop with range - Learn Python 3 - Snakify
Often the program needs to repeat some block several times. That's where the loops come in handy. There are for and while loop operators in Python, in this lesson we cover for. for loop iterates over any sequence.
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ python-for-loop-tutorial
Python for Loop: A Beginner's Tutorial โ€“ Dataquest
March 10, 2025 - To create a Python for loop, you start by defining an iteration variable and the iterable object you want to loop through. The iteration variable temporarily holds each item from the iterable during each loop.
๐ŸŒ
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.