Hi, I need to find the appropriate list operations.
example:
x = [1, 2, 3]
y = x
y[1] += 2
print(x)
>> [1, 4, 3]
How can I have y become the same list as x without x being influenced y?
I want the example to return [1, 2, 3] and let y be defined by x and be able to do any operation I want on y.
If i am not clear let me know thx.
>>> x = [1,2,3]
>>> y = x
>>> z = x[::]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
>>> z
[1, 2, 3]
>>> x[0] = 4
>>> x
[4, 2, 3]
>>> y
[4, 2, 3]
>>> z
[1, 2, 3]
>>> id(x)
140222264135304
>>> id(y)
140222264135304
>>> id(z)
140222264168648
in your example y = x does not create new list, y reference the same object as x. In my example you can see they have the same id (i.e. they are the same object). I showed one of the possible methods to copy/clone a list. There are also other options see
https://stackoverflow.com/a/2612815/4046632
you can also replace y = x with y = list(x)
This creates a new y list that is an exact copy of list x.
Can I ask here what is the difference between
z=x[::]
and
z=x[:]
If there is one.
Only for the knowledge.
Thx for the fast responses this helps me a lot. got a lot of replacing to do now xD.
(Feb-28-2018, 05:22 PM)Mario793 Wrote: [ -> ]Can I ask here what is the difference between
z=x[::]
and
z=x[:]
If there is one.
Only for the knowledge.
Also, as someone learning Python where would I find the meanings of this syntax ":" and "::".
Being told to just use them doesn't really explain why they work or exactly what they do.