Check if element is list python

Contents

  • Introduction
  • Example 1: Check if Element is in List
  • Example 2: Check if Element is not in List
  • Summary

Python Check if Element is present in List

Check if element is list python

You can write a condition to check if an element is present in a list or not using in keyword.

The syntax of condition to check if the element is present in given list is

element in list

The above condition returns True if the element is present in the list. Else, if returns False.

Example 1: Check if Element is in List

In the following program, we will check if element 'a' is present in list {'a', 'e', 'i', 'o', 'u'}. We will use the condition specified above along with Python If-Else statement.

Python Program

vowels = {'a', 'e', 'i', 'o', 'u'} element = 'a' if element in vowels: print(element, 'is in the list of vowels.') else: print(element, 'is not in the list of vowels.')Run

Output

a is in the list of vowels.

Example 2: Check if Element is not in List

You can also check the inverse of the above example. Meaning, you can check if an element is not present in the list.

To write a condition for checking if element is not in the list, use not operator in the syntax as shown below.

element not in list

In the following program, we will check if element 'b' is not present in list {'a', 'e', 'i', 'o', 'u'}.

Python Program

vowels = {'a', 'e', 'i', 'o', 'u'} element = 'b' if element not in vowels: print(element, 'is not in the list of vowels.') else: print(element, 'is in the list of vowels.')Run

Output

b is not in the list of vowels.

Summary

In this tutorial of Python Examples, we learned how to check if an element is in list, or if an element is not in list.

  • Python List without Last Element
  • How to Access List Items in Python?
  • Python Program to Find Smallest Number in List
  • Python How to Create an Empty List?
  • Python Get Index or Position of Item in List
  • How to Sort Python List?
  • Python Count the items with a specific value in the List
  • Python Check if List Contains all Elements of Another List
  • Python Traverse List except Last Element
  • How to Insert Item at Specific Index in Python List?