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:

But I am wondering if there a more Pythonic way of doing this.


Something like this:

In [22]: x = [1,2,3,4]

In [23]: y = [1,4,7,8]

In [24]: x += [ item for item in y if item not in x]

In [25]: x
Out[25]: [1, 2, 3, 4, 7, 8]

+= acts as list.extend, so the above code is equivalent to :

In [26]: x = [1,2,3,4]

In [27]: lis = [ item for item in y if item not in x]

In [28]: x.extend(lis)

In [29]: x
Out[29]: [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).

Need Your Help

Download android-ndk-r9-linux-x86

android linux ubuntu android-ndk ubuntu-10.04

I am trying to find somewhere link to download android-ndk-r9-linux-x86 but unfortunately all my tries failed.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.