Simple Method to Search a Python List

April 4, 2008

Let’s say you have a list of objects of type Individual and that list is called individuals.

The Individual type contains an ID, name, and email address.

Let’s say you have an ID and want to get the corresponding Individual object from the list. How would you go about doing that?

match = [ind for ind in individuals if ind.id == theID]

Entry Filed under: Python, Tip. Tags: .

3 Comments Add your own

  • 1. Pythonista  |  November 19, 2008 at 6:55 pm

    A) you mean == not =
    B) this is inefficient if the item is near the front of a long list.
    You could avoid that with a generator expression:
    try:
    match = (ind for ind in individuals if ind.id == theID).next()
    except:
    # fail action
    though I find this harder to comprehend at a glance.

  • 2. jaslin  |  September 13, 2009 at 2:42 pm

    I have a list of sorted ids to find whether there are matches in theID list. Will this next() restart from the position of the last successful match? I can always sort theID to speed up the matching.

  • 3. utah_guy  |  September 14, 2009 at 12:47 pm

    I’ve never used the next() method. But i would imagine it would do what you’re saying. But the best way is to give it a try.

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Archives

Top Posts