Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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] = 100print 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.

Solution 2:

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

Post a Comment for "Creating A New List From Elements Of An Other List, Referencing The Elements Of The Latter"