How to take two lists and combine them excluding any duplicates?
A slightly more efficient way to do it:
>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]
# New way
>>> list(set(first + second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.42 µs per loop
# Old way
>>> list(set(first) | set(second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.83 µs per loop
The new way is more efficient because it has only one set() instead of 2.
Use a set
.
>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]
>>> third = list(set(first) | set(second)) # '|' is union
>>> third
[1, 2, 3, 4, 5, 6, 7]