[Tutor] List intersect

Patrick Hall pathall at gmail.com
Mon Sep 27 21:30:01 CEST 2004

Hi folks,

On Mon, 27 Sep 2004 11:52:56 -0700 (PDT), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:

> An alternative way to solve the uniqueness problem is to use dictionaries
> or sets to maintain a unique list of elements.  All of the tutorials on:
>     http://www.python.org/topics/learn/non-prog.html
> should cover how to use dictionaries.

Here's one such approach:

def collect_unique(inputlist):
    """Use a dictionary to return a list
     of unique elements in inputlist"""
    seen = {}
    for element in inputlist:
        if element not in seen:
            seen[element] = 1
    unique = seen.keys()
    unique.sort() # just for readability in this case
    return unique

if __name__ == "__main__":
    userlists = \
(['buser', 'usera', 'userb', 'userc'],
 ['userb', 'userc', 'cuser', 'userc'],
 ['usera', 'duser', 'userb', 'userb'],
 ['userc', 'userc', 'userb', 'userb'],
 ['userc', 'userb', 'auser', 'userb'])

    # flatten into one big list
    biglist = []
    for userlist in userlists:

    unique_list = collect_unique(biglist)    
    print unique_list # or whatever.

I believe one can also do this sort of thing with Sets in more recent Pythons. 

By the way, does anyone know if using Set intersections is an
efficient way to handle this sort of thing?


More information about the Tutor mailing list