Hello everybody,
I want to know how to find an element in list without iteration
Hello everybody,
I want to know how to find an element in list without iteration
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
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