I am new to stack overflow so please excuse me if I am not clear.
aim: to write a program that would remove the elements that are present in preceding nested lists
here is the list:
gang=[[1], [7], [11], [13], [2, 4, 6, 8, 10, 12, 14], [3, 6, 9, 12, 15], [6, 12], [5, 10, 15]]
desired output: gang=[[1], [7], [11], [13], [2, 4, 6, 8, 10, 12, 14], [3, 6, 9, 15], [5, 10]]
attempt:
for i in range(1,len(gang)):
elem=gang[i]
for j in range(len(elem)):
for hey in range(i):
if elem[j] in gang[hey]:
elem.pop(j)
explanation of the attempt:
1)to traverse through list gang, I used a for loop (range is 1,len(gang) bcs 0th element wont be changed as it is the first one in the list)
2)I have declared a variable, 'elem' which equates to gang[i] i.e. the elements of gang from gang[1] to gang[-1]
3)Now, to traverse through the elements of the elements i.e. the elements of each nested list, I have used another for loop
4)the last for loop (for hey in range(i)) is used so that I can confirm if elem[j] i.e. element of nested list, exists in preceding nested lists, and if the condition is satisfied elem[j] would be removed
expected output:
gang=[[1], [7], [11], [13], [2, 4, 6, 8, 10, 12, 14], [3, 6, 9, 15], [5, 10]]
output:
if elem[j] in gang[hey]:
IndexError: list index out of range
question: why is this error showing? potential fix for it? any better way to achieve aim?