# Help with understanding difference between these codes

## Summary:

I don't understand why the first code won't change the list x, while the second code does change the list. Could someone explain?
Python:
#Code nr.1
x=[1,2]
def double(l):
return [a*2 for a in l]
double(x)
print(x)

#Code nr.2
def f(x):
x[0]=x[0]+1
return x
x=[3]
f(x)
print(x)

## Answers and Replies

Related Programming and Computer Science News on Phys.org
PeterDonis
Mentor
2019 Award
The first code returns a newly constructed list whose elements are the elements of the original list multiplied by two. That doesn't change anything about the original list. Try having print(double(x)) instead of just double(x) and see what happens.

The second code doesn't construct a new list, it sets the first element of the list to its previous value plus 1.

Kolika28
PeterDonis
Mentor
2019 Award
Note also that in the second code, f(x) returns the list x, but that return value isn't needed since you already have a variable pointing to the list x. It's a good general practice in Python that a function that mutates an object in place, instead of constructing a new object, should not return anything. That makes it clear that the function is not constructing anything new.

Kolika28
Ibix
[x for x in mylist] is a copy of mylist. Your first function uses this to create a modified copy, which it returns and you don't store or display. Your second function edits the list in place. You return the edited list and forget that too, but because you've edited it in place the original list is modified.

Edit: beaten to it by Peter, I see.

Kolika28
Thank you so much, both of you! I understand now ! :)

jedishrfu
Mentor
If you were to say:

x=double(x)

then x would be changed.

Kolika28