Lists are a mutable data type. If I have sublists inside a 2d list that have multiple references to the same object, the fact that changing any one makes changes in others suggests a question: am I able to extract information about linked sublists?
To explain, let's consider a 2d list:
import random
lst = [[0] for i in range(9)] # create list of 9 sublists with value inside
lst
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]] .
Each sublist pointing to the same object 0
, but independently. If any given sublist's contents change, the other sublists contents will remain stable. The fact that all IDs are different proves this point:
[id(i) for i in lst]
[139963231930640, 139963235043920, 139963236442592, 139963222312992, 139963783242688, 139963234936784, 139963233636256, 139963233634176, 139963233635056] .
Now let's create a random sample of objects:
indcs = random.sample(range(9), 9)
and then modify the sublists using the following function:
def mutables(a):
for i in range(len(a) - 1):
lst[a[i+1]] = lst[a[i]]
lst[a[i]][0] += 1
mutables(indcs[:3])
mutables(indcs[3:6])
mutables(indcs[6:])
lst
[[2], [2], [2], [2], [2], [2], [2], [2], [2]] .
The list now contains 3 groups of 3 sublists, each element of a group pointing to the same object. There are only 3IDsx3 in lst
:
[id(i) for i in lst]
[139963231930640, 139963235043920, 139963236442592, 139963235043920, 139963236442592, 139963231930640, 139963235043920, 139963231930640, 139963236442592] .
If we change, e.g., the third element of a list, it changes each element of a group:
lst[2][0] += 1
lst
[[2], [2], [3], [2], [3], [2], [2], [2], [3]] .
Here, the sublists (2,4,8) are changed. The 2nd(0,5,7) and 3rd(1,3,6) groups behave the same way:
lst[0][0] += 1
lst
[[3], [2], [3], [2], [3], [3], [2], [3], [3]]
lst[1][0] += 1
lst
[[3], [3], [3], [3], [3], [3], [3], [3], [3]] .
The change of an integer values inside sublists did not change IDs:
[id(i) for i in lst]
[139963231930640, 139963235043920, 139963236442592, 139963235043920, 139963236442592, 139963231930640, 139963235043920, 139963231930640, 139963236442592],
but adding 1
every time a new group member arrives provides useful information on the group size.
The crux of my question is, while the information about link between the sublists is retained, how to extract the indices of each group ((2,4,8),(0,5,7),(1,3,6)) without needing to refer to indcs
and how it was originally grouped: [:3:6:]
? I could change the 1st sublist value, track changes in others and pop them in a loop, but this information should be implicitly available on the basis of which an element in a group mutates. Is there any way to collect it? E.g., I can get id(name)
of a sublist and try to find linked sublists by one of the methods in described here or here, but these options return values, not their names.