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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With