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.

Answer from Alfe on Stack Overflow
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

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… More on discuss.python.org
🌐 discuss.python.org
12
1
August 24, 2020
Modifying a list in a Python function - Stack Overflow
It appears that the list is being modified as intended inside the function, however, the changes are not being applied outside the function to myList. What's going on here and how can I fix it? ... Python is pass by assignment for passing arguments inside the function. More on stackoverflow.com
🌐 stackoverflow.com
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
python - Modify list elements by passing it to a function - Stack Overflow
"(In Python) arguments are passed ... passed, the caller will see any changes the callee makes to it (items inserted into a list)." docs.python.org/3/tutorial/controlflow.html#defining-functions... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
People also ask

How can I modify a list inside a function in Python?
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.
🌐
sqlpey.com
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
What is the difference between pass by reference and pass by value in Python?
A: Python uses pass by reference for mutable objects like lists and dictionaries, but the reference itself is passed by value, meaning reassigning the variable inside the function does not affect the original object.
🌐
sqlpey.com
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
🌐
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...
🌐
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
🌐
Dummies
dummies.com › article › technology › programming-web-design › python › how-to-modify-lists-in-python-203522
How to Modify Lists in Python | dummies
January 25, 2017 - Python has added another element to List1. However, using the insert() function lets you add the new element before the first element. The new list, List2, is a precise copy of List1. Copying is often used to create a temporary version of an existing list so that a user can make temporary modifications to it rather than to the original list.
Author:
🌐
Dataquest
dataquest.io › home › blog › tutorial: why functions modify lists and dictionaries in python
Tutorial: Why Functions Modify Lists, Dictionaries in Python
April 9, 2023 - And while most of the data types we’ve worked with in introductory Python are immutable (including integers, floats, strings, Booleans, and tuples), lists and dictionaries are mutable. That means a global list or dictionary can be changed even when it’s used inside of a function, just like we saw in the examples above.
Find elsewhere
🌐
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...
🌐
DNMTechs
dnmtechs.com › modifying-lists-in-python-3-functions
Modifying Lists in Python 3 Functions – DNMTechs – Sharing and Storing Technology Knowledge
Within the function, we iterate over each element of the list using a for loop and multiply each element by 2. By directly modifying the list, we avoid the need to create a new list and return it. Python provides several built-in methods that allow us to modify lists directly.
🌐
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 ...
🌐
Iditect
iditect.com › faq › python › modifying-a-list-inside-a-function-in-python.html
Modifying a list inside a function in python
In Python, you can modify a list inside a function by directly accessing and modifying the elements of the list. Lists are mutable objects, which means you can change their content even when they are passed to functions.
Top answer
1 of 3
3

Python is pass by assignment for passing arguments inside the function. When you do

thisArray = thisArray[1:]

inside your function, you re-bind the passed argument to a new object created inside your function and proceed to mutate that copy created after slicing instead, rather than modifying your argument thisArray. To get the modified value, one way is to return this modified list from your function:

def reverse_this(thisArray):
    saved_first = thisArray[0]
    thisArray = thisArray[1:]
    thisArray.reverse()
    thisArray.insert(0,saved_first)
    return thisArray

myList = ['foo', 1,2,3,4,5]
myList = reverse_this(myList)
print('after:', myList)

Other way is to modify the list's contents (assign to the slice) rather than re-binding the list itself:

def reverse_this(thisArray):
    saved_first = thisArray[0]
    thisArray[:] = thisArray[1:] # assign to the sliced list's contents
    thisArray.reverse()
    thisArray.insert(0,saved_first)
2 of 3
2

thisArray is re-assigned to a new list object by slicing, so any changes after that don't affect the original list passed into the function. Note the instance IDs of the lists:

def reverse_this(thisArray):
    
    saved_first = thisArray[0]
    print(f'thisArray pre-slice:  {id(thisArray):#x}')
    thisArray = thisArray[1:]
    print(f'thisArray post-slice: {id(thisArray):#x}')
    thisArray.reverse()
    thisArray.insert(0,saved_first)

myList = ['foo', 1,2,3,4,5]
print(f'myList pre-call:      {id(myList):#x}')
reverse_this(myList)
print(f'myList post-call:     {id(myList):#x}')
print('after:', myList)
myList pre-call:      0x1e2f5713500
thisArray pre-slice:  0x1e2f5713500  # parameter refers to original list
thisArray post-slice: 0x1e2f5753800  # thisArray refers to new list
myList post-call:     0x1e2f5713500  # original list isn't changed.
after: ['foo', 1, 2, 3, 4, 5]

In Python, variables are names of objects. If you mutate an object, all names of that object "see" the change. A slice makes a new object, and in this case the name was reassigned to the new object.

To fix it, assign the slice into the full range of the original list, which mutates the original list instead of creating a new one:

def reverse_this(thisArray):
    
    saved_first = thisArray[0]
    thisArray[:] = thisArray[1:]   # replace entire content of original list with slice.
    thisArray.reverse()            # thisArray still refers to original list here.
    thisArray.insert(0,saved_first)

myList = ['foo', 1,2,3,4,5]
reverse_this(myList)
print('after:', myList)
after: ['foo', 5, 4, 3, 2, 1]

When assigning to a slice, a section of a list is replaced in place with another list. It doesn't necessarily have to be the same size.

Another example:

>>> s = list(range(10))
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> id(s)
2339680033664
>>> s[4:7] = [10,10]           # replace indices 4 up to but not including 7
>>> s
[0, 1, 2, 3, 10, 10, 7, 8, 9]
>>> id(s)                           # id didn't change
2339680033664
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-change-list-item
Python - Change List Item - GeeksforGeeks
July 23, 2025 - Using Indexing we update a specific item in the list by simply assigning a new value to the desired index. ... The statement a[1] = 25 modifies the element at index 1 (second position) of the list, replacing 20 with 25.
🌐
Codecademy
codecademy.com › forum_questions › 551a424a937676ff44000944
Lists in Python with Funtions | Codecademy
e.g. in this case, list does not change · def change_list(lst): lst.append(4) list = [1, 2, 3]: change_list(list) ... both modify the list, and you are always dealing with the original until you overwrite the variable with a reference to some ...
Top answer
1 of 5
1

Each item in a list has an associated index, starting from zero. As you probably know, you can access the items in the list using those indexes:

>>> magicians_names = ['Marv', 'Wowzo', 'Trickster', 'Didlo']
>>> magicians_names[0]
'Marv'

You can also modify the list items using those indexes:

>>> magicians_names[0] = 'Jerry Boomfang'
>>> magicians_names[0]
'Jerry Boomfang'

So what you need to do is loop through both the list and its indexes, modifying as you go. Which is exactly what the enumerate function is for.

>>> for index, magician in enumerate(magicians_names):
...     magicians_names[index] += ' is great!'
...
>>> magicians_names
['Jerry Boomfang is great!', 'Wowzo is great!', 'Trickster is great!', 'Didlo is great!']
2 of 5
0

Hope this helps. The [:] retains the original list by making a copy or slice of the the original list to be used in the function being called. The exercises in the book are 8-9 to 8-11 on page 150 Crash course in Python.

def meta_mags(show_mags, great_mags):
    """(Change regular show magicians to Great magicians by moving them 
     to another list using a function meta_mags)"""
    while show_mags:
        change_mags = show_mags.pop()
        # show the change from one list show_mags to great_mags
        print("Great magicians: " + change_mags.title())
        great_mags.append(change_mags)


def show_great_mags(great_mags):
    """Print --The Great--- after each great_mags magicians name"""
    for great_mag in great_mags:
        print(great_mag.title() +" The Great will be performing tonight !") 


show_mags = ['alice', 'david', 'carolina']
great_mags = []
meta_mags(show_mags[:], great_mags)
show_great_mags(great_mags) 
print(show_mags)
🌐
Stack Overflow
stackoverflow.com › questions › 68432202 › modifying-list-inside-function
python - Modifying list inside function - Stack Overflow
July 18, 2021 - Why after function change_list() is finished list_a ID is not pointing the same address as list_b ID? while inside function both are the same… ... list_a = ... and list_a[0] = ... are two very different things. The former creates a local variable, the latter invokes a method through a global variable (list_a.__setattr__(0, ...)). ... Save this answer. ... Show activity on this post. This is because Python passes all arguments by passing object references, not names or references to names.
Top answer
1 of 4
3

Except for what Sylvain said, of course it still didn't work because a process can't modify the variables of its parent process. The variables are copied when a new process is created.

You can try the following example.

from multiprocessing import Process

def modify(idx, li):
    li[idx] = 'hello'

a = [0] * 3 

p = Process(target=modify, args=(1, a))
p.start()
p.join()
print a

modify(1, a)
print a

The result will be:

[0, 0, 0]
[0, 'hello', 0]
2 of 4
2

There are many reason why it is not working.

First, in the function read_occupation, you are changing the binding of a local variable. The original object is left untouched. On the contrary, in get_p_values, you are modifying the object (the [] operator call the __setitem__ function of the object that change the internal representation). A better idea in this case would be to use a proper object.

If you want to change the whole content of the list in read_occupation, you can use the list splicing operator to assign to the whole list:

def read_occupation(matrix):
    matrix[:] = [ [1, 2, 3] ]

BTW, if you call you function read_occupation the caller will probably expect it not to change its parameter. You should probably rename it update_occupation or something like that.

Second, when you create your variables, via multiplication, you get a list where every index contains a reference to the same item. The code p = [ [0] ] * 3 is equivalent to:

>>> l = [0]          # Naming the list for more clarity
>>> p = [ l, l, l ]  # Each index points to the same list `l`

Third, the Process class expect a tuple (or in fact an object following the iterable protocol) for its args parameter. You are not passing a tuple, but a single item that happens to be a list of one int (which is why you get a TypeError exception). You need to use the following syntax to pass a tuple:

# Please note the comma after the closing bracket, it is important
p1 = Process( target=read_occupation, args=( matrix[ index     ], ) )

# In python, the syntax for a tuple is weird for tuple of size < 2
#  . tuple of 0 item:  ()
#  . tuple of 1 item:  (1,)
#  . tuple of 2 items: (1, 2)

Fourth, you use multiprocessing.Process that spawn a new process in which your code is executed. There is no communication back in your code (I don't know if it is possible to communicate back from this process to the original one). So the variable in the original code is not modified.