Help with understanding difference between these codes

  • Thread starter Thread starter Kolika28
  • Start date Start date
  • Tags Tags
    Difference
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 1K views
Kolika28
Messages
146
Reaction score
28
TL;DR
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)
 
Physics news on Phys.org
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.
 
  • Like
Likes   Reactions: Kolika28
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.
 
  • Like
Likes   Reactions: Kolika28
[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.
 
  • Like
Likes   Reactions: Kolika28
Thank you so much, both of you! I understand now ! :)