Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a short contains function for lists?

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 
like image 385
Joan Venge Avatar asked Oct 17 '12 12:10

Joan Venge


People also ask

Can a list contain a function?

Functions can be stored as elements of a list or any other data structure in Python.

Can you use LEN () on a list?

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.

Can a list contain string?

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.

How do you see if a list contains an item Python?

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.


1 Answers

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.

like image 141
defuz Avatar answered Oct 22 '22 23:10

defuz