+ 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!
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)
+ 3
Thorsten, if you still need an explanation, please put your code in playground and link it here. Thanks!
+ 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..
+ 2
Yes this is the affectation is the value passed for the argument no the reference
It is true
+ 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]
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.
0
You mean
a=1
b=a
a=2
Now a =2, b=1?
0
Right, that's what I meant