'Removing duplicity of items in list of lists based on a specific index #Python
I have the following lists:
lista = [1,2,3,5]
listb = [1,5,2,6]
listc = [3,5,1,6]
mainList = [lista,listb,listc]
I'd like to remove listb from mainList since it contains the same element as lista at index position[0].
Kinda like the code below, however, applied to every list contained in mainList. basically, remove all lists with index 0 duplicity while maintaining the first one.
if lista[0] == listb[0]:
mainList.remove(listb)
#But to include duplicity in for all elements in mainList.
Anybody? Thanks in advance!
Solution 1:[1]
You can use the code below-
lista = [1,2,3,5]
listb = [1,5,2,6]
listc = [3,5,1,6]
mainList = [lista,listb,listc]
ml_final = mainList.copy() #make a copy of the main list, this would be the final list
first_ele = [] #make empty list where first elements of all the lists are added
for i in range(len(mainList)):
temp = mainList[i][0]
if temp in first_ele:
ml_final.pop(i)
else:
first_ele.append(temp)
#output
print(ml_list)
#[[1, 2, 3, 5], [3, 5, 1, 6]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lsr729 |
