Standard ways to get union, intersection, difference of lists?

  • Thread starter =?ISO-8859-1?Q?Mickel_Gr=F6nroos?=
  • Start date
?

=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=

Hi!

Are there any standard list methods for getting the intersection and
difference of two lists? (The union is easy ("list1.extend(list2)"),
unless you want it to contain unique values.)

Here is what I would like to have:

list1 = [1,2,3]
list2 = [3,4]

list3 = list1.intersection(list2)
(list3 is now [3])

list3 = list1.difference(list2)
(list3 is now [1,2])

list3 = list2.difference(list1)
(list3 is now [4])

I realize I could quite easily implement this myself, but I was hoping for
a built-in solution.

Cheers,

/Mickel
 
P

Paul Rudin

Mickel" == Mickel Grönroos said:
> Hi! Are there any standard list methods for getting the
> intersection and difference of two lists? (The union is easy
> ("list1.extend(list2)"), unless you want it to contain unique
> values.)
[snip]

> I realize I could quite easily implement this myself, but I was
> hoping for a built-in solution.

You might want to take a look at the sets module in Python 2.3. It's
not exactly what you ask for since sets.Sets are not lists - but they
do support these operations and can easily be converted to or from
lists.
 
E

Erik Max Francis

Mickel said:
Are there any standard list methods for getting the intersection and
difference of two lists? (The union is easy ("list1.extend(list2)"),
unless you want it to contain unique values.)

If you have Python 2.3 available, why not use a set?
import sets
s1 = sets.Set([1, 2, 3])
s2 = sets.Set([3, 4])
s1.intersection(s2) Set([3])
s1.difference(s2) Set([1, 2])
s2.difference(s1)
Set([4])
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top