I want to create a new list from a previous one’s elements, but without copying them. That is what happens:
In [23]: list = range(10)
In [24]: list2 = list[0:4]
In [25]: list
Out[25]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [26]: list2
Out[26]: [0, 1, 2, 3]
Though the elements of the lists seem to have the same id,
In [29]: id(list[1])
Out[29]: 145137840
In [30]: id(list2[1])
Out[30]: 145137840
After editing one element, I don’t change the object that is referenced, but the value for that site on the list.
In [31]: list[1] = 100
In [32]: id(list[1])
Out[32]: 145138628
In [33]: id(list2[1])
Out[33]: 145137840
In [34]: list
Out[34]: [0, 100, 2, 3, 4, 5, 6, 7, 8, 9]
In [35]: list2
Out[35]: [0, 1, 2, 3]
I want to use the list2 as a representative of some particular elements of list. I’m guessing that there should be a good way to compose a list that gives me the chance to edit the values of the elements of list, when I also change the value for list.
Anywhere
1or another small number is in a variable, it will always have the same id. These numbers only exist once, and since they’re immutable, it’s safe for them to be referenced everywhere.Using slice syntax
[:]always makes a copy.When you set
list1[1], you’re not changing the value of what’s stored in memory, you’re pointinglist1[1]to a new location in memory. So since you didn’t pointlist2[1]to a different location, it still points to the old location and value.Never name a variable
listsince there is a built in function by that name.If you want to do what you’re talking about with minimal modification, try:
You just need to always add [0] after the item you want to reference. As the lists don’t get replaced, just the item in them, and
list2points to the list not the item, it will stay in sync.