As for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
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
Filtering a collection
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.
Finding the first occurrence
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])
Finding the location of an item
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]
Answer from Niklas B. on Stack OverflowAs for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
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
Filtering a collection
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.
Finding the first occurrence
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])
Finding the location of an item
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]
If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:
first_or_default = next((x for x in lst if ...), None)
Why doesn't python lists have a .find() method?
Adding the method find() to list - Ideas - Discussions on Python.org
Finding a sublist anywhere within a list
Okay, first of all, <= doesn't detect sublists, it checks if the list is "lower or equal". For lists that means that beginning from the first item, every item is compared until two items are found that are different. Like [1, 2] < [1, 3] is True, since 2 < 3. This shouldn't be used to check for sublists though, because [1, 1] <= [1, 2, 3] is also True, but [1, 1] is not a sublist of [1, 2, 3]
Python doesn't ship a sublist function, so you have to write one by yourself, like this
def isSublist(a, b):
if len(a) > len(b):
return False
for i in range(0, len(b) - len(a) + 1):
if b[i:i+len(a)] == a:
return True
return Falsethis will check if a is a sublist of b, so isSublist([2, 3], [1, 2, 3, 4]) should return True. This works by walking through the second list (the list in which we're searching) and comparing the sublist b[i:i+len of the sublist we're searching] to the sublist we're searching (if you don't know that syntax, you should read on slice notations in the Python doc).
I hope I could help, if you have more questions feel free to ask :)
More on reddit.combeautifulsoup - How to get_text from item retrieved using find_all ('tag', 'class')
Videos
Doesn't it make sense for lists to have a find method?
class MyList(list):
def find(self, func):
for i in self:
if func(i):
return i
return None
# or raise ValueError?
users = [
{
'id': 1,
'name': 'john',
},
{
'id': 2,
'name': 'anna',
},
{
'id': 3,
'name': 'bruce',
}
]
my_list = MyList(users)
user_2 = my_list.find(lambda i: i['id'] == 2)
print(user_2) # {'id': 2, 'name': 'anna'}