0

I want to be able to remove an element from a list of list when a field in a list is duplicated in python3.

I.E:

Remove from the following list of lists when the second field is duplicated. From

[["John","France"], ["Mike", "France"], ["Ana","Italy"]]

To

[["John","France"], ["Ana","Italy"]]

Edit: I have tried the following loop, but I am looking forward to a more efficient way if it exists.

for element in consult_array:
    for other_elements in consult_array:
        if element[1] == other_elements[1]:
            if element != other_elements:
                consult_array.pop(element)
kederrac
  • 16,819
  • 6
  • 32
  • 55
Dani Gonzalez
  • 93
  • 1
  • 7

2 Answers2

2
data = [["John", "France"], ["Mike", "France"], ["Ana", "Italy"]]

output = []
already_seen_countries = set()

for item in data:
    country = item[1]
    if country not in already_seen_countries:
        output.append(item)
        already_seen_countries.add(country)

print(output)  # [['John', 'France'], ['Ana', 'Italy']]
Michael H.
  • 3,323
  • 2
  • 23
  • 31
  • If anyone is facing this problem in the future: To remove it from the original list, I put this code in a function with the list as arg, and I am returning the output and assinging it to the original list. – Dani Gonzalez Mar 04 '20 at 15:16
0

if you like one line solutions:

l = [["John","France"], ["Mike", "France"], ["Ana","Italy"]]
list(t for t in {e[1]: e for e in l[::-1]}.values())[::-1]

output:

[['John', 'France'], ['Ana', 'Italy']]
kederrac
  • 16,819
  • 6
  • 32
  • 55