mehmet.ali.anil
mehmet.ali.anil

Reputation: 525

Creating a new list from elements of an other list, referencing the elements of the latter

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.

Upvotes: 1

Views: 5069

Answers (2)

agf
agf

Reputation: 176750

Anywhere 1 or 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 pointing list1[1] to a new location in memory. So since you didn't point list2[1] to a different location, it still points to the old location and value.

Never name a variable list since there is a built in function by that name.

If you want to do what you're talking about with minimal modification, try:

list1 = [[x] for x in range(10)]
list2 = list1[:4]
list1[1][0] = 100
print list2

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 list2 points to the list not the item, it will stay in sync.

Upvotes: 3

warvariuc
warvariuc

Reputation: 59594

Use mutable types as list elements. For example:

>>> a = [[1], [2]]
>>> b = a[1]
>>> a
[[1], [2]]
>>> b
[2]
>>> b[0]=[3]
>>> a
[[1], [[3]]]
>>> b
[[3]]
>>> 

Upvotes: 1

Related Questions