why the second def dont work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

why the second def dont work?

i tried this.. def f_a(my_list,i): my_list[i]=0 def f_b(my_list, i): my_list=[i] lst=[1,2,3,4] f_a(lst,1) f_b(lst,2) print ( lst ) ... i got [1,0,3,4] ; why i didn't got just [2]?

23rd Sep 2018, 10:41 AM
sama baluom
sama baluom - avatar
6 Answers
+ 1
Exactly, that's why the output of Merts code is "false". You can print the ids in different places of the code to gain more insight: https://code.sololearn.com/co902AUy51P5/?ref=app You see that the ids are always the same like in the main scope, but different if you set something new to the same variable name (i.e. another address is reserved for this and if you want to use it, you would return it from the function)
23rd Sep 2018, 11:43 AM
Matthias
Matthias - avatar
+ 7
Use "my_list[:] = [i]" f_b doesn't work because it creates a list and overrides lst reference(?) You will probably understand it if you run this code: def f_b(my_list, i): id1 = id(my_list) my_list=[i] print(id(my_list) == id1) lst = [1, 2, 3, 4] f_b(lst,2) and I think your question is similar to this: https://stackoverflow.com/questions/850795/different-ways-of-clearing-lists
23rd Sep 2018, 11:14 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 2
It works, put a print(my_list) in your second def. I think part of the list is mutable, but not the whole list.
23rd Sep 2018, 11:01 AM
Paul
Paul - avatar
+ 2
sama baluom As Mert Yazıcı already tried to show with his code: If you write my_list = something it has a different id, i.e. a new object is created. It lives on another memory address. While in-place operations like in f_a or if you write my_list[:] it will operate on the object of the original address.
23rd Sep 2018, 11:29 AM
Matthias
Matthias - avatar
0
thank you !, that worked, but..why? i thought it should print lst first that is [1,0,3,4] then print [2]..
23rd Sep 2018, 11:06 AM
sama baluom
sama baluom - avatar
0
got it 🙃 it don't has same id like the list in f_a right? and thank you
23rd Sep 2018, 11:34 AM
sama baluom
sama baluom - avatar