Python Forum
list syntax - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: list syntax (/thread-8617.html)



list syntax - blazersnake - Feb-28-2018

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.


RE: list syntax - buran - Feb-28-2018

>>> 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


RE: list syntax - Robo_Pi - Feb-28-2018

you can also replace y = x with y = list(x)

This creates a new y list that is an exact copy of list x.


RE: list syntax - Mario793 - Feb-28-2018

Can I ask here what is the difference between
z=x[::]
and
z=x[:]
If there is one.
Only for the knowledge.


RE: list syntax - blazersnake - Feb-28-2018

Thx for the fast responses this helps me a lot. got a lot of replacing to do now xD.


RE: list syntax - Robo_Pi - Feb-28-2018

(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.


RE: list syntax - buran - Feb-28-2018

working with list, I assume you are familiar with slicing
https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation