Skip to main content

Finding Elements

Note☆ Learning Objectives
  • Verify if an element is inside a list.
  • Find the index of an element inside a list.

When you work with lists, a very common task is checking whether a specific value is inside the list. You might want to locate a single value, confirm that something exists, or find items that match a certain condition.

Using the in Operator

The in operator is the simplest way to check if an element is present in a list.

Example

Let’s say we have this delightful list

test = [1,2,3,4,5,6]

If you want to check whether the value 3 is in the list, you can write:

test = [1,2,3,4,5,6]
if 3 in test:
    print ("Found value 3")
else:
    print("3 not found")
Found value 3

Similarly, we can also check if 9 is in test:

test = [1,2,3,4,5,6]
if 9 in test: # wow
    print ("Found value 9")
else:
    print("9 not found")
9 not found

Similarly, we can also check if 11 is not in test:

test = [1,2,3,4,5,6]
if 11 not in test:
    print ("11 isn't in the list")
else:
    print("11 is in the list")
11 isn't in the list

Finding the index of an element

If finding the specific position of an element in the list, you may use the index() method as such:

test = [1,2,3,4,5,6]

idx_of_3 = test.index(3)

print(f"Here's the index of 3: ", idx_of_3)
Here's the index of 3:  2

Resources