[Tutor] Lists...

Archimedes gibbs05@flash.net
Wed, 30 May 2001 22:04:52 -0500


----- Original Message ----- 
From: "Andrew Wilkins" <toodles@yifan.net>
To: <tutor@python.org>
Sent: Wednesday, May 30, 2001 9:36 PM
Subject: [Tutor] Lists...


> Hi people,
> 
> Is there a way of returning the intersection of two lists?
> Eg. [1,2,'3',4.0,'x'] & [1,8,'3',9,10,'x'] to return [1,'3','x']

Sure.

Here's how to do it by brute force:

    >>> a = [1,2,'3',4.0,'x']
    >>> b = [1,8,'3',9,10,'x']
    >>> def intersection(a, b):
    ...        result = []
    ...        for item in a:
    ...            if item in b:
    ...                result.append(item)
    ...        return result
    ... 
    >>> intersection(a, b)
    [1, '3', 'x']

> Andrew Wilkins

Good luck.

Sam