views:

232

answers:

3

Hello everybody,

I want to know how to find an element in list without iteration

+8  A: 

The mylist.index("blah") method of a list will return the index of the first occurrence of the item "blah":

>>> ["item 1", "blah", "item 3"].index("blah")
1
>>> ["item 1", "item 2", "blah"].index("blah")
2

It will raise ValueError if it cannot be found:

>>> ["item 1", "item 2", "item 3"].index("not found")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

You can also use the in keyword to determine if an item is in a list (but not the location):

>>> "not found" in ["item 1", "blah", "item 3"]
False
>>> "item 3" in ["item 1", "blah", "item 3"]
True

As Harper Shelby commented, Python will still have to iterate internally to find the items, but the index or in methods may be slightly quicker than doing it in Python, as the data-structures are implemented in C.. but more importantly,

"x" in mylist

..is much tidier than..

found = False
for cur in mylist:
    if cur == "x":
        found = True
dbr
This is going to have to iterate under the covers - you can't search a list without iteration *somewhere*.
Harper Shelby
+4  A: 

You can also use in syntax:

>>> l = [1,2,3]
>>> 1 in l
True
atc
+5  A: 

This is a somewhat strange question. Do you want a hotline with $someDeity, or do you want another function to do the iteration for you, or do you want a more efficient way to test membership?

In the first case I cannot help you. In the second case, have a look at the documentation on lists, specifically the index method. In the third case, create a set and use the in keyword. Note that set creation only pays off if you intend to search through the list many times.

>>> l = [1, 2, 3]
>>> l.index(2)
1
>>> 3 in l
True
>>> ls = set(l)
>>> 3 in ls
True
Stephan202
You don't need to use a set to use the `in` keyword.. >>> (3 in [1,2,3]) == True
dbr
@dbr: That's true, as my example already shows. set allows for a more efficient membership test, which is why I show both methods.
Stephan202
Converting the list to a set takes a lot of time. Using timeit.Timer, `3 in [1,2,3]` took 0.174s, `3 in set([1,2,3])` took 0.953s. With a larger list (1000 items) it took ever longer (9seconds for set, 1second for list). Moving the set([1,2,3]) code into to the timer setup code (so it's only run once) makes `x in set()` slightly quicker, about 0.01 seconds (total, when repeated 1million times!). I think converting to a set is probably more inefficient than just using the list, unless you need the other set() features..
dbr
Ah, of course if one wants to do only one lookup set creation does not pay off. It does in the case of a lot of lookups. (I should have noted this trivial fact, I guess. I'll update the answer.)
Stephan202