1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2004
Location
Isle of dogs
Posts
68
Rep Power
14

#### Python Set manipulation

A=['one','two','three','four']
B=['one','two','three','four','oddvalue1','oddvalue2']

I should know this , but is an efficient way I can get values from set B that is not in A

In this example I want the answer ['oddvalue1','oddvalue2']
2. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
London, England
Posts
1,585
Rep Power
1377
Yes, use sets. In Python 2.3 a 'sets' module was added to the standard library. In 2.4 the set was promoted to a buitin data type (but the sets module was retained for backward compatibility).

Code:
```>>> from sets import Set
>>> A = ['one','two','three','four']
>>> B = ['one','two','three','four','oddvalue1','oddvalue2']
>>> setA = Set(A)
>>> setB = Set(B)
>>> # get set of elements in B that are not in A
>>> setB - setA
Set(['oddvalue2', 'oddvalue1'])
>>> #convert it back into a list:
>>> list(setB - setA)
['oddvalue2', 'oddvalue1']```
Dave - The Developers' Coach
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2004
Posts
394
Rep Power
55
Hi!

You can also do it with a list comprehension:
Code:
`print [x for x in B if x not in A]`
Regards,
mawe
4. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2004
Location
Isle of dogs
Posts
68
Rep Power
14
Thanks very much, my mistake was to not using the set command while creating the list, I thought lists and sets are the same.
5. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2004
Posts
73
Rep Power
14
filter(lambda x: x not in A , B)