The answer depends on the desired semantics a - b .
If you need only the first elements, then slicing is the natural way to do this:
In [11]: a = [1, 2, 3] In [12]: b = [4 , 5] In [13]: ab = a + b In [14]: ab[:len(a)] Out[14]: [1, 2, 3]
If, on the other hand, you want to remove items from the first list that are not found in the second list:
In [15]: [v for v in ab if v not in b] Out[15]: [1, 2, 3]
The second type of operation is more naturally expressed using sets:
In [18]: set(ab) - set(b) Out[18]: set([1, 2, 3])
Note that in general this does not preserve the order of the elements (since the set is unordered). If ordering is important, and b is likely to be long, converting b to a set can improve performance:
In [19]: bset = set(b) In [20]: [v for v in ab if v not in bset] Out[20]: [1, 2, 3]
For dictionaries, an “add” operation in place already exists. It is called dict.update() .
source share