Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list syntax
#1
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.
Reply
#2
>>> 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
Reply
#3
you can also replace y = x with y = list(x)

This creates a new y list that is an exact copy of list x.
Reply
#4
Can I ask here what is the difference between
z=x[::]
and
z=x[:]
If there is one.
Only for the knowledge.
Reply
#5
Thx for the fast responses this helps me a lot. got a lot of replacing to do now xD.
Reply
#6
(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.
Reply
#7
working with list, I assume you are familiar with slicing
https://stackoverflow.com/questions/5092...e-notation
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Syntax Hitso 4 2,249 May-26-2020, 10:51 AM
Last Post: hussainmujtaba
  What is the correct syntax for list items that need to contain a quotation mark, etc? KaisoArt 7 3,487 Sep-14-2019, 05:26 AM
Last Post: buran
  syntax error on list.sort() jjordan33 3 3,202 Jul-10-2019, 04:57 PM
Last Post: jefsummers
  Help with list Syntax. jarrod0987 2 2,625 Jan-13-2018, 01:11 PM
Last Post: jarrod0987

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020