Python Tutorial (33) – Example: Determine whether an element exists in a list

Time: Column:Python views:244

Define a List and Check if an Element is in the List

This Python code demonstrates various methods for checking if a specific element exists in a list.

Example 1

test_list = [1, 6, 3, 5, 3, 4]

print("Check if 4 is in the list (using loop):")

# Check using a loop
for i in test_list:
    if i == 4:
        print("Exists")

print("Check if 4 is in the list (using 'in' keyword):")

# Check using 'in' keyword
if 4 in test_list:
    print("Exists")

Output:

Check if 4 is in the list (using loop):
Exists
Check if 4 is in the list (using 'in' keyword):
Exists

Example 2

# Initialize lists
test_list_set = [1, 6, 3, 5, 3, 4]
test_list_bisect = [1, 6, 3, 5, 3, 4]

print("Check if 4 is in the list (using set() + 'in'):")

# Convert list to set and check using 'in'
test_list_set = set(test_list_set)
if 4 in test_list_set:
    print("Exists")

print("Check if 4 is in the list (using count()):")

# Check using count()
if test_list_bisect.count(4) > 0:
    print("Exists")

Output:

Check if 4 is in the list (using set() + 'in'):
Exists
Check if 4 is in the list (using count()):
Exists

Explanation:

  1. Example 1 demonstrates two methods:

    • Checking for existence using a loop.

    • Checking for existence using the in keyword, which is more concise and efficient.

  2. Example 2 introduces additional methods:

    • Converting the list to a set and checking using the in keyword. This can be faster for large lists but requires conversion.

    • Using the count() method to check if an element is present. If the count is greater than 0, the element exists in the list.