Pythonic's best method for conditionally adding lists

I am sure this question came up earlier, but I could not find an exact example.

I have 2 lists and you want to add the second to the first, only the values ​​no longer exist.

So far I have had working code, but I was wondering if it was better, more "Pythonic" did it:

>>> list1
[1, 2, 3]
>>> list2
[2, 4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4]

EDIT Based on the comments made, this code does not satisfy the addition only once, that is:

>>> list1 = [1,2,3]
>>> list2 = [2,4,4,4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4, 4, 4]

How can I finish only:

[1, 2, 3, 4]
+4
source share
2 answers

You can use the built-in type set:

list(set(list1).union(list2))

, list1, list1:

list1=list(set(list1).union(list2))

. , .

, !

+4

, collections.OrderedDict,

from collections import OrderedDict
from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(OrderedDict.fromkeys(chain(list1, list2)))
# [1, 2, 3, 4]

, set

from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(set(chain(list1, list2)))
# [1, 2, 3, 4]
+5

Source: https://habr.com/ru/post/1530424/


All Articles