Is a list comprehension appropriate here?

I need to add items to the list only if the current iterated item is not already listed.

>>> l = [1, 2]
>>> for x in (2, 3, 4):
...     if x not in l:
...             l.append(x)
... 
>>> l
[1, 2, 3, 4]

against

>>> l = [1, 2]
>>> [l.append(i) for i in (2, 3, 4) if i not in l]
[None, None]
>>> l
[1, 2, 3, 4]

Understanding the list gives the result - this is what I want, just the returned list is useless. Is this a good example of using lists?

Iteration is a good solution, but I wonder if there is a more idiomatic way to do this?

+5
source share
4 answers

You can do:

l.extend((i for i in (2,3,4) if i not in l))

This solution still works if the added list is not unique.

+5
source

, , , , ; list.__contains__ - O (n), - O (n 2). , set.__contains__ - O (log n), - . , n , O (log n), O (n log n), , O (n 2) n ( , 100 ).

>>> l = [1, 2]
>>> seen = set(l)
>>> for x in (2, 3, 4):
...     if x not in seen:
...         seen.add(x)
...         l.append(x)
... 
>>> l
[1, 2, 3, 4]
>>> 
+7

. 3- .

l , , in l

+3

:

orig = [1,2]
ext = [2,3,4]
orig.extend(filter( lambda x,p=set(orig):not(x in p or p.add(x)),ext ))

.

BTW, O (n * log (n)).

+3
source

All Articles