Reputation:
In Python 3, is there a way to do a list comprehension where some object, x, gets inserted into the list if it's not already in the same list. I basically want the code to do this:
my_list = ["aa", "aa", "bb", "bb"]
new_list = [c for c in my_list if c not in new_list] ## Add each c from my_list into new_list if c is not already in new_list.
I don't want to delete duplicates in my_list
and I strictly need a list comprehension technique. Is there any way that I can do this?
Upvotes: 1
Views: 4184
Reputation: 12669
You can do it in many ways in one line without modifying origional list, Here are some ways :
using list comprehension :
my_list = ["aa", "aa", "bb", "bb"]
new_list=[]
[new_list.append(i) for i in my_list if i not in new_list]
using set:
my_list = ["aa", "aa", "bb", "bb"]
print(list(set(my_list)))
Using itertools:
import itertools
print(list(map(lambda x:x[0],itertools.groupby(my_list))))
using collections:
import collections
print(collections.Counter(my_list).keys())
using dict.fromkeys():
print(list(dict.fromkeys(my_list)))
Upvotes: 0
Reputation: 19104
O(N) space and O(N) time by using an auxiliary set:
seen = set()
[seen.add(x) or x for x in my_list if x not in seen]
returns
['aa', 'bb']
Upvotes: -1
Reputation: 95908
Here's a horribly inefficient way to accomplish this:
>>> [x for i, x in enumerate(my_list) if x not in my_list[:i]]
['aa', 'bb']
It's O(N^2) time and O(N) space.
Don't use this. Write good code.
A similarly inefficient solution:
>>> [x for i, x in enumerate(my_list) if my_list.index(x) == i]
['aa', 'bb']
Upvotes: 3