I have come across this:
item = someSortOfSelection()
if item in myList:
doMySpecialFunction(item)
but sometimes it does not work with
If you are going to check if value exist in the collectible once then using 'in' operator is fine. However, if you are going to check for more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 12 times faster than using 'in' operator.
Here is an example of code using Python 3.8 and above syntax:
import bisect
from timeit import timeit
def bisect_search(container, value):
return (
(index := bisect.bisect_left(container, value)) < len(container)
and container[index] == value
)
data = list(range(1000))
# value to search
true_value = 666
false_value = 66666
# times to test
ttt = 1000
print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")
t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)
print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")
Output:
bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71
Instead of using list.index(x)
which returns the index of x if it is found in list or returns a #ValueError
message if x is not found, you could use list.count(x)
which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count()
is that it doesn't break your code or require you to throw an exception for when x is not found
You may want to use one of two possible searches while working with list of strings:
if list element is equal to an item ('example' is in ['one','example','two']):
if item in your_list: some_function_on_true()
'ex' in ['one','ex','two'] => True
'ex_1' in ['one','ex','two'] => False
if list element is like an item ('ex' is in ['one,'example','two'] or 'example_1' is in ['one','example','two']):
matches = [el for el in your_list if item in el]
or
matches = [el for el in your_list if el in item]
then just check len(matches)
or read them if needed.
Check there are no additional/unwanted whites space in the items of the list of strings. That's a reason that can be interfering explaining the items cannot be found.
Definition and Usage
the count()
method returns the number of elements with the specified value.
Syntax
list.count(value)
example:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
Question's example:
item = someSortOfSelection()
if myList.count(item) >= 1 :
doMySpecialFunction(item)
As for your first question: that code is perfectly fine and should work if item
equals one of the elements inside myList
. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.
As for your second question: There's actually several possible ways if "finding" things in lists.
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in
operator for that:
3 in [1, 2, 3] # => True
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter
doesn't return a list, but a generator-like object.
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else
clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration
if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
For lists, there's also the index
method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index
always returns the lowest index:......
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate()
instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]