How to check if an element is in a list or not in python ?

Active June 01, 2020    /    Viewed 1434    /    Comments 0    /    Edit


Examples of how to check if an element is in a list or not in python:

1 -- Create a liste

Lets create for instance the following list:

>>> l
['a', 'b', 'c', 'd', 'e', 'f']

2 -- Check if an element is in the list

To check if the element 'c' is in the list called here l, a solution is to use the following logical expression:

>>> 'c' in l
True

check now if 'g' is in the list

>>> 'g' in l

returns here:

False

Can then be used with if, illustration:

>>> if 'c' in l: print('do something !')

returns:

do something !

3 -- Check if an element is not in the list

To check if an element is not in a list, a solution is to use the expression 'not in', example:

>>> 'h' not in l
True

4 -- Another examples

Example 1

>>> l = ['Coucou','Salut','Bonjour','He']
>>> 'Salut' in l
True
>>> 'Hello' in l
False

Example 2

>>> l = [3,1,7,5]
>>> 7 in l
True
>>> 2 in l
False

5 -- References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount