Back

Checking if something is in a list

In and not in
We can easily do a Boolean test to see if something is a member of a list or not. Each test will return either True or False. Can you predict what will be printed out for each print statement in the following code:

places = ["Glasgow", "London", "Derby", "Leicester", "Leeds"]
print ("Glasgow" in places)
print ("Derby" in places)
print ("Plymouth" in places)
print ("Colchester" in places)
print ("Ely" not in places)
print ("London" not in places)

Nested lists
We can also examine nested lists quite cleverly in Python. Here is a list of tuples, and the second element in each tuple is a list. We can examine both elements in each tuple at once. Here is an example.

#Count how many students are taking Computing
students = [
        ("Dave", ["Computing", "Maths", "French"]),
        ("Pete", ["Maths", "German", "French", "Law"]),
        ("Ali", ["Computing", "PE", "English", "Maths"]),
        ("Mary", ["English", "French", "German", "Spanish"]),
        ("Jack", ["Computing", "Latin", "Law", "Greek", "RE"])]

# Count how many students are taking CompSci
count = 0
for (student, course) in students:
    if "Computing" in course:
    count += 1

print("Students taking Computing:", count)

Use a visualiser
You could use www.pythontutor.com to visualise how the code for this works. 

Back