A list as an alternative to if/elif/else

How not to program

monkey1.py

Please type a year: 2019
2019 was the year of the pig.
Please type a year: 2000
2000 was the year of the dragon.
Please type a year: 1955
1955 was the year of the sheep.
Please type a year:

Easier with a list.

monkey2.py

The output is the same:

Please type a year: 2019
2019 was the year of the pig.
Please type a year: 2000
2000 was the year of the dragon.
Please type a year: 1955
1955 was the year of the sheep.
Please type a year:

How not to program: another example

findmonth1.py

Please type a month, e.g., January: July
Thank you, July is month number 7.
Please type a month, e.g., January: Juli
Bad month "Juli".

Easier with a list.

findmonth2.py

The None in line 15 is a dummy value. Use it where you have no value to put there. Our only purpose in storing None in the list is to make January have index 1 instead of index 0.

Please type a month, e.g., January: July
Thank you, July is month number 7.
Please type a month, e.g., January: Juli
Bad month "Juli".

Easier to search a list with the index function.

findmonth3.py

Please type a month, e.g., January: July
Thank you, July is month number 7.
Please type a month, e.g., January: Juli
Bad month "Juli".

What would
months[::-1].index(month)
do? What would
months[::-1].index(month) - 1
do?

Search a list with in or not in

If you don’t need the index number, it’s faster to search with in and not in.

if month in months:
    print(f"Thank you, {month} is in months.")
else:
    print(f'Bad month "{month}".')

Search a list with any and all

If you don’t need the index number, and you’re searching for the number 0 or the empty string "", it’s easier to call the functions any and all.

numbers = [0, 0, 0, 10, 0]

if any(numbers):
    print("The list contains a non-zero value.")
else:
    print("All the numbers are 0.")
The list contains a non-zero value.
strings = ["", "", "", "hello", ""]

if any(strings):
    print("The list contains a non-empty value.")
else:
    print("All the strings are the empty string.")
The list contains a non-empty value.
numbers = [20, 30, 10, 0, 50]

if all(numbers):
    print("All the numbers are non-zero.")
else:
    print("The list contains 0.")
The list contains 0.
strings = ["hello", "goodbye", "", "hello again", "Hiya fellah!"]

if all(strings):
    print("All the strings are non-empty.")
else:
    print("The list contains the empty string.")

Search a dictionary

We’ll have a faster way to search the months when we learn about dictionaries.