I need to keep my data in a list of lists, but want to edit elements in the lists based on their overall position.
For instance:
mylist = [['h','e','l','l','o'], ['w','o','r','l','d']]
I want to change position 5 as if it was all one list resulting in:
[['h','e','l','l','o'], ['change','o','r','l','d']]
This is for very large lists and lots of mutations so speed is essential!
Advertisement
Answer
Here is the solution of your’s question
# initializing list input_list = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']] print("The initial list is : " + str(input_list)) length: int = 0 # define position(global index) where you want to update items in list change_index = 5 ## global starting index of sublist [0,5] sub_list_start_index: list = list() for sub_list in input_list: sub_list_start_index.append(length) length += len(sub_list) # check if index we want to change is <= global list index and if change_index <= length - 1 and change_index >= max(sub_list_start_index): sub_list_index = int(change_index - max(sub_list_start_index)) input_list[input_list.index(sub_list)][sub_list_index] = 'change' print("Updated list : " + str(input_list))
Output:
The initial list is : [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']] Updated list : [['h', 'e', 'l', 'l', 'o'], ['change', 'o', 'r', 'l', 'd']]