List item without iteration

I want to know how to find an item in a list without iterating

-7


a source to share


3 answers


mylist.index("blah")

method
in the list will return the index of the first occurrence of the "blah" element:

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

      

It will increment the ValueError if not 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 a keyword in

to determine if an item is in the list (but not in a 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 over internally to find elements, but the index or methods might be slightly faster than doing it in Python since the data structures are implemented in C .. but more importantly,

"x" in mylist

      

.. much more neat than ..

found = False
for cur in mylist:
    if cur == "x":
        found = True

      

+9


a source


This is a somewhat strange question. Do you need a hotline with $someDeity

, or do you want another function to iterate for you, or do you want a more efficient way to test your membership?

In the first case, I cannot help you. In the second case, look at the documentation in the lists , specifically the method index

. In the third case, create set

and use a keyword in

. Note that creating a set only pays off if you intend to search the list multiple times.



>>> l = [1, 2, 3]
>>> l.index(2)
1
>>> 3 in l
True
>>> ls = set(l)
>>> 3 in ls
True

      

+5


a source


You can also use the syntax in

:

>>> l = [1,2,3]
>>> 1 in l
True

      

+4


a source







All Articles