Loops, Conditions, and Lists
Check if an item is in the list
Sometimes you want to find out if some item is in the list. You can use the same pattern as before, but with a different change to the variable in the loop body.
Hereβs an example:
# Does the list have string "Python" in it?
languages = ["Ruby", "JavaScript", "C", "Rust", "Smalltalk", "Clojure", "Python"]
has_match = False
for language in languages:
if language == "Python":
has_match = True
print(has_match)
Itβs the same pattern as before, but with an if
statement in Step 2.
- πΒ Step 1: Create a variable called
has_match
, which starts asFalse
- π Step 2: Loop through the strings in the list. If the string matches, set
has_match
toTrue
- πΒ Step 3: Print out the
has_match
variable
Filter a list
Sometimes, you want to find only the values in your list that meet a certain condition.
Again, we can use the three step pattern. The variable we are updating will be a new list, with just the filtered values.
numbers = [62, 60, 53, 53, 33, 3, 25, 61, 36, 1, 69, 55, 56, 39, 32, 76, 20, 62, 47]
# Write a program to find all the even numbers in the list
evens = []
for element in numbers:
if element % 2 == 0:
evens.append(element)
print(evens) # [62, 60, 36, 56, 32, 76, 20, 62]
We use an if
statement and the modulo operator to find the even values, and add them to the list.
Practice: Sum of Odds
Solution (try for at least 10-20 minutes before looking)
numbers = [62, 60, 53, 53, 33, 3, 25, 61, 36, 1, 69, 55, 56, 39, 32, 76, 20, 62, 47]
total = 0
for n in numbers:
if n % 2 == 1:
total += n
print(total)
Smallest Item
Finding the minimum value in a list uses the same pattern. Step through the elements of the list, and update a variable that is tracking the current minimum value.
Each time through the loop, check if the number is smaller than the current minimum value. If it is, then itβs the new minimum value.
We can use the first value in the list as the initial value of the minimum.
numbers = [62, 60, -53, 53, 33, -3, 25, 81, 36, 1, 69, 55, 56, 39, -32, -76, 20, 62, 47]
minimum = numbers[0]
for number in numbers:
if number < minimum:
minimum = number
print(minimum) # -76
With one small change, this same code works to find the largest value instead.
Practice: Interactive Minimum
Solution (try for at least 10-20 minutes before looking)
numbers = int(input("How many numbers will you enter? "))
i = 0
minimum = float('inf')
for i in range(numbers):
x = int(input("Enter a number: "))
# check whether x is smaller than minimum, and reassign minimum to it if so
if x < minimum:
minimum = x
print("The smallest number is:", minimum)