How to Check if Key Exists in List Python?

By Hardik Savani October 30, 2023 Category : Python

Hi Friends,

I am going to explain to you example of how to check if key exists in list python. This example will help you python check if key exists in list. This article will give you a simple example of python check if key exists in json list. If you have a question about python list check if key exists then I will give a simple example with a solution. So, let's follow a few steps to create an example of python check if key exists list.

If you want to check key exists or not in the python list then I will give you the following examples. we will use "in" with list for checking key exist or not.

Without any further ado, let's see the code examples below.

You can use these examples with python3 (Python 3) version.

Example 1:

main.py

# Created new List
myList=[ 1, 2, 3, 4, 5, 6 ]
  
# Key for check id exist or not
key=3
  
# Checking key exist or not in myList var
if key in myList:
    print("Given key is exist in List.")
else:
    print("Given key is not exist in List.")

Output:

Given key is exist in List.

Example 2:

main.py

# Created new List
myList=[ 1, 2, 3, 4, 5, 6 ]
  
# Checking key exist or not in myList var
for i in myList:
    if(i == 3):
        print("Given key is exist in List.")

Output:

Given key is exist in List.

Example 3:

main.py

# Created new List
myList=[ 1, 2, 3, 4, 5, 6 ]
  
# Checking key exist or not in myList var
if (3 in myList):
    print("Given key is exist in List.")
else:
    print("Given key is not exist in List.")

Output:

Given key is exist in List.

I hope it can help you...

Tags :
Shares