Appending new values to a python list
Lets say I have two lists:
x = [1,2,3,4] y = [1,4,7,8]
I want to append to x any values in y that are not already in x. I can do this easily with a loop:
for value in y: if value not in x: x.append(value)
But I am wondering if there a more Pythonic way of doing this.
Something like this:
In : x = [1,2,3,4] In : y = [1,4,7,8] In : x += [ item for item in y if item not in x] In : x Out: [1, 2, 3, 4, 7, 8]
+= acts as list.extend, so the above code is equivalent to :
In : x = [1,2,3,4] In : lis = [ item for item in y if item not in x] In : x.extend(lis) In : x Out: [1, 2, 3, 4, 7, 8]
Note that if the size of list x is huge and your list x/y contain only immutable(hashable) items then you must use sets here, as they will improve the time complexity to O(N).