Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
December 18th, 2004, 08:23 AM
 Tkinter_Bell
Contributing User

Join Date: Oct 2004
Location: Isle of dogs
Posts: 68
Time spent in forums: < 1 sec
Reputation Power: 10
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
December 18th, 2004, 10:39 AM
 DevCoach
Contributing User

Join Date: Feb 2004
Location: London, England
Posts: 1,585
Time spent in forums: 2 Weeks 4 Days 2 h 58 m 23 sec
Reputation Power: 1372
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
December 18th, 2004, 02:02 PM
 mawe
Contributing User

Join Date: Nov 2004
Posts: 394
Time spent in forums: 1 Day 10 h 6 m 47 sec
Reputation Power: 51
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
December 18th, 2004, 02:11 PM
 Tkinter_Bell
Contributing User

Join Date: Oct 2004
Location: Isle of dogs
Posts: 68
Time spent in forums: < 1 sec
Reputation Power: 10
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
December 18th, 2004, 08:19 PM
 weam
Contributing User

Join Date: Aug 2004
Posts: 73
Time spent in forums: 1 Day 5 m 3 sec
Reputation Power: 10
filter(lambda x: x not in A , B)

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Python Set manipulation