Given a nested list, you can access the elements with something like
data = [[12, 15], [21, 22], [118, 546], [200, 1200]]
assert data[0][0] == 12
The issue is that in this case, I want to index into a nested list with a "list of indexes", with dynamic at runtime length. For example, the "list of indexes" for above would be [0,0]
I want this general type of function
def nested_list_assignment(nested_list, list_of_indices, value):
and would work something like
# passes this basic test
data = [[12, 15], [21, 22], [118, 546], [200, 1200]]
assert data[0][0] == 12
nested_list_assignment(data, [0, 0], 0)
assert data[0][0] == 0
I have a working impl like
def nested_list_assignment(nested_list, list_of_indices, value):
# ill handle this case later
assert len(list_of_indices) > 0
if len(list_of_indices) == 1:
nested_list[list_of_indices[0]] = value
else:
nested_list_assignment(nested_list[list_of_indices[0]], list_of_indices[1:], value)
but I’m curious if Python gives any constructs for this, or just a standard library function for this in general.
>Solution :
There’s no standard Python function or operator for this, but something like this works generically as long as you’re sure that everything being indexed is itself indexable with the elements of indices:
def list_assignment(indexable, indices, value):
for i in indices[:-1]:
indexable = indexable[i]
indexable[indices[-1]] = value
data = [[12, 15], [21, 22], [118, 546], [200, 1200]]
list_assignment(data, [0, 0], 0)
print(data)
Output:
[[0, 15], [21, 22], [118, 546], [200, 1200]]
This works for anything you can index:
d = {
'a': {
'b': 1,
'c': 2,
},
'd': 3
}
list_assignment(d, ['a', 'c'], 42)
print(d)
Output:
{'a': {'b': 1, 'c': 42}, 'd': 3}
Keep in mind that this can go wrong in several ways:
- an empty list of indices fails
- a list with too many indices, or missing indices, fails