+ 2

Assigning a list and change it

Hello, I recently had a problem with two list elements. First I iterated a list from 0 to 9 and named it mylist. Afterwards I wanted to copy this list (target = mylist) and changed it afterwards with random.shuffle(mylist). My new list target changed with it as well. I could solve it by changing target = mylist to target = list(mylist). I still don't know why it acts that way and want to know, if anyone could explain it to me? Thanks a lot!

15th Apr 2020, 12:49 PM
Thorsten Mielke
Thorsten Mielke - avatar
8 Réponses
+ 2
By assigning both list points to same address. So changes happens in both list..... Use copy() method like list=[1,2,3,4] List=list.copy() print(list, List)
15th Apr 2020, 1:02 PM
Jayakrishna 🇮🇳
+ 3
Thorsten, if you still need an explanation, please put your code in playground and link it here. Thanks!
15th Apr 2020, 4:05 PM
Lothar
Lothar - avatar
+ 2
Thorsten Mielke These List, and tuples are heterogeneous types, contains a collection of elements with successive memory locations.. So collection are returns starting address when assigning.. Pass by refference types. But integer, and strings are contains single value, pass by value types... In python, there May be some other reasons which I don't know..
15th Apr 2020, 1:40 PM
Jayakrishna 🇮🇳
+ 2
Yes this is the affectation is the value passed for the argument no the reference It is true
15th Apr 2020, 8:26 PM
HADÈS
HADÈS - avatar
+ 1
That is because you are stored it the reference not the value of the first list. list.copy() is a method to copy all the elements of a list. target = mylist.copy() You can use this syntax to copy all the values too: target = [*mylist]
16th Apr 2020, 1:09 AM
Jonathan Alvarado
Jonathan Alvarado - avatar
0
Ok, thanks! Jayakrishna🇮🇳 Do you know why it is different with strings or integers? The copy method fits perfectly for this purpose, by the way.
15th Apr 2020, 1:11 PM
Thorsten Mielke
Thorsten Mielke - avatar
0
You mean a=1 b=a a=2 Now a =2, b=1?
15th Apr 2020, 1:28 PM
Jayakrishna 🇮🇳
0
Right, that's what I meant
15th Apr 2020, 1:31 PM
Thorsten Mielke
Thorsten Mielke - avatar