I found this in the docs: https://docs.python.org/3/tutorial/controlflow.html#for

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy.

I was wrong in my first response, when iterating through a list it returns the actual items in that list. However, it seems they cannot be edited directly while they are being iterated through. This is why iterating through the integers the length of the list works.

As for why the .reverse() function works, I think it's because it is affecting a list instead of a value. I tried to use similar built in functions on nonlist datatypes like .replace() on strings and it had no effect.

All of the other list functions I tried worked: .append(), .remove(), and .reverse() as you showed. I'm not sure why this is, but I hope it clears up what you can do in for loops a bit more.

Answer to old question below:

The way you are using the for loops doesn't affect the actual list, just the temporary variable that is iterating through the list. There are a few ways you can fix this. Instead of iterating through each element you can can count up to the length of the list and modify the list directly.

c = [1,2,3]
for n in range(len(c)):
    c[n] += 3
print(c) 

You can also use the enumerate() function to iterate through both a counter and list items.

c = [1,2,3]
for n, x in enumerate(c):
    c[n] = x + 3
print(c) 

In this case, n is a counter and x is the item in the list.

Finally, you can use list comprehension to generate a new list with desired differences in one line.

c = [1, 2, 3]
d = [x + 3 for x in c]
print(d)
Answer from Aeolus on Stack Overflow
Top answer
1 of 4
25

I found this in the docs: https://docs.python.org/3/tutorial/controlflow.html#for

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy.

I was wrong in my first response, when iterating through a list it returns the actual items in that list. However, it seems they cannot be edited directly while they are being iterated through. This is why iterating through the integers the length of the list works.

As for why the .reverse() function works, I think it's because it is affecting a list instead of a value. I tried to use similar built in functions on nonlist datatypes like .replace() on strings and it had no effect.

All of the other list functions I tried worked: .append(), .remove(), and .reverse() as you showed. I'm not sure why this is, but I hope it clears up what you can do in for loops a bit more.

Answer to old question below:

The way you are using the for loops doesn't affect the actual list, just the temporary variable that is iterating through the list. There are a few ways you can fix this. Instead of iterating through each element you can can count up to the length of the list and modify the list directly.

c = [1,2,3]
for n in range(len(c)):
    c[n] += 3
print(c) 

You can also use the enumerate() function to iterate through both a counter and list items.

c = [1,2,3]
for n, x in enumerate(c):
    c[n] = x + 3
print(c) 

In this case, n is a counter and x is the item in the list.

Finally, you can use list comprehension to generate a new list with desired differences in one line.

c = [1, 2, 3]
d = [x + 3 for x in c]
print(d)
2 of 4
10

If you want to keep it consice without creating an additional variable, you could also do:

c = [1,2,3] 
print(id(c)) 
c[:] = [i+3 for i in c] 
print(c, id(c))

Output:

2881750110600
[4, 5, 6] 2881750110600
Top answer
1 of 4
94

If you assign something to the variable list_arg, it will from then on point to the new value. The value it pointed to before that assignment (your original list) will stay unchanged.

If you, instead, assign something to elements of that list, this will change the original list:

list_arg[:] = list(a)

This will make your code work as you wanted it.

But keep in mind that in-place changes are hard to understand and probably can confuse the next developer who has to maintain your code.

2 of 4
12

What I think you are asking is why after calling f(a), when f re-assigns the a you passed, a is still the "old" a you passed.

The reason for this is how Python treats variables and pass them to functions. They are passed by reference, but the reference is passed by value (meaning that a copy is created). This means that the reference you have inside f is actually a copy of the reference you passed. This again implies that if you reassign the variable inside the function. It is a local variable existing only inside the function; re-assigning it won't change anything in outside scopes.

Now, if you rather than reassigning the local variable/reference inside f (which won't work, since it's a copy) perform mutable operations on it, such as append(), the list you pass will have changed after f is done.

See also the question How do I pass a variable by reference? which treats the problem and possible solutions in further detail.

TL;DR: Reassigning a variable inside a function won't change the variable you passed as an argument outside the function. Performing mutable operations on the variable, however, will change it.

Discussions

It seems that you can edit a global list in a function. (But you can’t edit a global variable. Without declaring global in the function) What’s the best practice for this list modification by a function ?
In my opinion, it's generally better to take the list as a parameter and then return a new list without changing the old one. It's less error-prone, more thread-safe (even if not completely, if the original list gets mutated somewhere), and any problems should be easier to identify because you know the source of the changes. Now, yes, this is more expensive in terms of computational requirements and takes more memory. If those are your primary worries, then you may want to mutate the list in place instead - but I say only do that if you know you need to, and you understand the consequences. Of course, if you're using a class then mutability is usually fine. Although you may still consider the pros and cons of making the class itself immutable, having its methods return new instances instead of mutating an existing one. More on reddit.com
🌐 r/learnpython
13
8
August 3, 2023
About the way to modify the list in-place in a function in Python - Stack Overflow
If I try to modify the 'board' list in-place in the way below, it doesn't work, it seems like it generate some new 'board' instead of modify in-place. def func(self, board): """ :type board: More on stackoverflow.com
🌐 stackoverflow.com
June 22, 2018
Why do my lists get modified when passed to a function?
In the following simplistic example variables x and y are assigned and passed into a function, where, under new names, they’re modified, summed and the result returned: x,y = 2,3 def some_function(a,b): z = a*2 + b*2 return z z = some_function(x,y) print(x, y, z) > 2 3 10 Naturally, x and ... More on discuss.python.org
🌐 discuss.python.org
12
1
August 24, 2020
Python modifying list within function - Stack Overflow
I am trying to let a function modify a list by passing the list's reference to it. The program below shows when I pass a list into the function, only a local variable is generated. Is there any way... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-change-list-item
Python - Change List Item - GeeksforGeeks
July 23, 2025 - Using a list comprehension, [x * 2 if x % 2 == 0 else x for x in a], we iterate over each element in the list. For each element: If the element is even (x % 2 == 0), we double it (x * 2). If the element is odd, we leave it unchanged. If we want to modify elements in place a for loop with enumerate() allows us to iterate through the list while keeping track of indices...
🌐
YouTube
youtube.com › tony staunton
Python: How to modifying a list in a function - YouTube
Explore the full course on Udemy (special discount included in the link): https://www.udemy.com/python3-a-beginners-quick-start-guide-to-python/?couponCode=
Published: November 4, 2018
Views: 3K
Find elsewhere
Top answer
1 of 2
4

You seem to understand the difference between these two cases, and want to know why Python makes you handle them differently?

I have to do something like this to modify it in-place, what's the reason?


Creating a new copy is something that has a value. So it makes sense for it to be an expression. In fact, list comprehensions would be useless if they weren't expressions.

Mutating a list in-place isn't something that has a value. So, there's no reason to make it an expression, and in fact, it would be weird to do so. Sure, you could come up with some kind of value (like, say, the list being mutated). But that would be at odds with everything else in the design of Python: spam.append(eggs) doesn't return spam, it returns nothing. spam = eggs doesn't have a value. And so on.


Secondarily, the comprehension style feeds very well into the iterable paradigm, which is fundamental to Python. For example, notice that you can turn a list comprehension into a generator comprehension (which gives you a lazy iterator over values that are computed on demand) just by changing the […] to (…). What useful equivalent could there be for mutation?

Making the transforming-copy more convenient also encourages people to use a non-mutating style, which often leads to better answers for many problems. When you want to know how to avoid writing three lines of nested statement to mutate some global, the answer is to stop mutating that global and instead pass in a parameter and return the new value.

Also, the syntax was copied from Haskell, where there is no mutation.


But of course all those "often" and "usually" don't mean "never". Sometimes (unless you're designing a language with no mutation), you need to do things in-place. That's why we have list.sort as well as sorted. (And a lot of work has gone into optimizing the hell out of list.sort; it's not just an afterthought.)

Python doesn't stop you from doing it. It just doesn't bend over quite as far to make it easy as it does for copying.

2 of 2
0

that is not modifying it in place. The list comprehension syntax [x for y in z] is creating a new list. The original list is not modified by this syntax. Making the name inside the function point to a new list won't change what list the name outside the function is pointing.

In other words, when calling a function python passes a reference to the object, not the name, so there is no easy way to change which object the variable name outside the function is refering to.

🌐
Iditect
iditect.com › faq › python › modifying-a-list-inside-a-function-in-python.html
Modifying a list inside a function in python
In this example, the function modify_list() takes a list as an argument and modifies it by appending an element and changing the value of the first element.
🌐
Python.org
discuss.python.org › python help
Why do my lists get modified when passed to a function? - Python Help - Discussions on Python.org
August 24, 2020 - In the following simplistic example variables x and y are assigned and passed into a function, where, under new names, they’re modified, summed and the result returned: x,y = 2,3 def some_function(a,b): z = a*2 + b*2 return z z = some_function(x,y) print(x, y, z) > 2 3 10 Naturally, x and y have not changed, but that is what happens if they’re lists: x = [[2,2]] y = [[3,3]] def some_function(a,b): z = a + b # concatenate lists for i in range(len...
🌐
sqlpey
sqlpey.com › python › 5-effective-strategies-to-modify-a-list-inside-a-function-in-python
5 Effective Strategies to Modify a List Inside a Function in Python
December 6, 2024 - A: To modify a list inside a function, use slice assignment or methods like .extend() to update the original list rather than reassigning the parameter within the function. A: Python uses pass by reference for mutable objects like lists and dictionaries, but the reference itself is passed by ...
🌐
Codecademy
codecademy.com › forum_questions › 52320d8180ff33534f000386
Modifying each element in a list in a function | Codecademy
Here is my code: n = [3, 5, 7] for i in range(0, len(n)): n[i] = n[i] * 2 # Don't forget to return your new list! def double_list(x): for...
🌐
pythontutorials
pythontutorials.net › blog › how-to-mutate-a-list-with-a-function-in-python
How to Mutate a List In-Place with a Python Function: Update Original List Without Reassignment — pythontutorials.net
Key Takeaway: In-place mutation preserves the original list’s identity; reassignment does not. For functions, we want in-place mutation to ensure the original list outside the function is updated. In Python, objects are classified as mutable (can be modified after creation) or immutable (cannot be modified).
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-4-organizing-data-collections › python-modifying-lists
Modifying Python Lists | Add, Remove, Change Items
This modifies the list in place, making it empty. The list variable still exists, it just contains no elements. Visual representation of list modifications starting with ['A', 'B', 'C']. Each step shows the result of applying a modification method. Understanding these methods for changing, adding, and removing items provides you with the tools needed to effectively manage dynamic collections of data using Python lists.
🌐
SitePoint
sitepoint.com › python hub › change list items
Python - Change List Items | SitePoint — SitePoint
The elements are rearranged in ascending order. The method modifies the original list in place.
🌐
W3Schools
w3schools.com › python › python_lists_change.asp
Python - Change List Items
To change the value of a specific item, refer to the index number.
🌐
Matt Bognar
homepage.divms.uiowa.edu › ~sriram › 16 › spring11 › 22C16Mar23.pdf pdf
M A R C H 2 3 Operations that modify Lists in Place
Operations that modify Lists in · Place · Lists and strings also have important differences · In Python some data types are mutable, i.e., they can be modified in · place. Of the data types we have seen so far, e.g., int, long, float, bool, str, and list, only list is mutable.