user8177336
user8177336

Reputation:

List Comprehension: Inserting x into the list if x is not in the list already?

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

Answers (3)

Aaditya Ura
Aaditya Ura

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

Alex
Alex

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

juanpa.arrivillaga
juanpa.arrivillaga

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

Related Questions