I see people are using any
to gather another list to see if an item exists in a list, but is there a quick way to just do something like this?
if list.contains(myItem): # do something
Functions can be stored as elements of a list or any other data structure in Python.
Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
Just like strings store characters at specific positions, we can use lists to store a collection of strings. In this tutorial, we will get a string with specific values in a Python list.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
You can use this syntax:
if myItem in some_list: # do something
Also, inverse operator:
if myItem not in some_list: # do something
It works fine for lists, tuples, sets and dicts (check keys).
Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With