Help with understanding difference between these codes

  • Thread starter Kolika28
  • Start date
  • #1
142
26

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

  • #2
PeterDonis
Mentor
Insights Author
2019 Award
31,228
10,120
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 Kolika28
  • #3
PeterDonis
Mentor
Insights Author
2019 Award
31,228
10,120
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 Kolika28
  • #4
Ibix
Science Advisor
Insights Author
6,931
5,844
[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 Kolika28
  • #5
142
26
Thank you so much, both of you! I understand now ! :)
 
  • #6
12,098
5,779
If you were to say:

x=double(x)

then x would be changed.
 
  • Like
Likes Kolika28

Related Threads on Help with understanding difference between these codes

  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
8
Views
1K
  • Last Post
Replies
4
Views
1K
  • Last Post
Replies
17
Views
3K
Replies
7
Views
2K
  • Last Post
Replies
4
Views
2K
Replies
20
Views
3K
  • Last Post
Replies
3
Views
2K
Top