Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Pythonic way to conditionally append lists

I'm sure this question has come up before, but I couldn't find an exact example.

I have 2 lists and want to append the second to the first, only of the values are not already there.

So far I have working code, but was wondering if there were a better, more "Pythonic" was of doing this:

>>> 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 comments made, this code does not satisfy adding only once, ie:

>>> 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 would I end up with only:

[1, 2, 3, 4]
like image 763
port5432 Avatar asked Jan 11 '23 01:01

port5432


1 Answers

If you want to maintain the order, you can use collections.OrderedDict like this

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]

If the order of the elements is not important, you can use the set like this

from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(set(chain(list1, list2)))
# [1, 2, 3, 4]
like image 56
thefourtheye Avatar answered Jan 13 '23 14:01

thefourtheye