0

How can I use list comprehension for the list unique?

original_list = [[1, 2, 3, 5], [2, 3, 5, 4], [0, 5, 4, 1], [3, 7, 2, 1], [1, 2, 1, 2]]
new_list = [elements for items in original_list for elements in items]
unique = []
for item in new_list:
    if item not in unique:
        unique.append(item)
print(unique)

cs95
  • 379,657
  • 97
  • 704
  • 746
  • @a121 For large lists, this implementation will be horribly inefficient. The correct way to do this is with a set comprehension. – Tom Karzes Jan 02 '21 at 07:29
  • You almost have the answer. You need to convert the list comprehension to a set and back to a list. `new_list = list({elements for items in original_list for elements in items}) ` will do the trick. – Joe Ferndz Jan 02 '21 at 07:31

1 Answers1

3

Use set comprehension:

uniques = {elements for items in original_list for elements in items}

will give you the set

{0, 1, 2, 3, 4, 5, 7}

You can convert it to a list if you want

uniques = list(uniques)
Jarvis
  • 8,494
  • 3
  • 27
  • 58