livepython.net
CHAPTER 09Python Lists
9.5  LIST TOOLS

Python List Functions: in, sort, min, max, sum

Check If an Item Is in a List with in

The in operator asks: "is this value somewhere in the list?" The answer is True or False. not in asks the opposite question.

Think of the guest list at a party door. The guard checks whether your name is on it before letting you in.

PYTHONedit me
guests = ["Sunny", "Rocky", "Lucky"]
print("Rocky" in guests)
print("sunny" in guests)
print("sunny" not in guests)
OUTPUT
True
False
True

The rules

  • value in list is True when at least one item equals the value.
  • value not in list is True when no item does.
  • The match must be exact: "sunny" is not "Sunny", and the text "5" is not the number 5.

in with if

in gives True or False, so it makes a perfect if condition (chapter 8). Here a café checks an order typed by the user:

PYTHONedit me
menu = ["tea", "coffee", "juice"]
order = input()
if order in menu:
    print(f"One {order} coming up!")
else:
    print(f"Sorry, no {order} today.")
OUTPUT
One coffee coming up!

Try typing lassi in the Input box.

Good: check before you remove

In topic 4, remove() stopped with a ValueError when the value was missing. With in, you check first:

PYTHONedit me
cart = ["milk", "eggs"]
if "bread" in cart:
    cart.remove("bread")
else:
    print("No bread in the cart")
OUTPUT
No bread in the cart

Avoid: calling remove() on a value that might not be there. One missing item would stop the whole program.

value in list is True when the list has that item. Check with in before you remove().

your turnPredict the output

What will this print?

nums = [1, 2, 3] print("2" in nums)
Your turn! What will this code show on the screen?
your turnFix the code

Make it print the list without an error: ['red', 'blue']

It should print: ['red', 'blue']

colors = ["red", "blue"]
colors.remove("green")
print(colors)
This code does not work yet. Fix it, then press Run.

Sort a List: sort() vs sorted()

Python can put a list in order for you. sort() sorts the list itself. sorted() leaves the list alone and gives you a new, sorted list.

Think of the books on your shelf. sort() is rearranging the books on the shelf. sorted() is writing the titles in order on a new piece of paper, while the shelf stays as it was.

PYTHONedit me
marks = [72, 95, 60, 88]
marks.sort()
print(marks)
marks.sort(reverse=True)
print(marks)
OUTPUT
[60, 72, 88, 95]
[95, 88, 72, 60]
PYTHONedit me
marks = [72, 95, 60, 88]
ranked = sorted(marks)
print(ranked)
print(marks)
OUTPUT
[60, 72, 88, 95]
[72, 95, 60, 88]

The rules

marks.sort()sorted(marks)
Changes marksyesno
Gives backNonea new sorted list
Biggest firstmarks.sort(reverse=True)sorted(marks, reverse=True)
  • Numbers sort from small to big.
  • Strings sort in alphabet order, and capital letters come first.
PYTHONedit me
fruits = ["mango", "Banana", "apple"]
print(sorted(fruits))
OUTPUT
['Banana', 'apple', 'mango']

To Python, every capital letter comes before every small letter. You'll learn to handle that in the Strings chapter.

Avoid: storing what sort() gives back

PYTHONedit me
marks = [72, 95, 60]
marks = marks.sort()
print(marks)
OUTPUT
None

Same trap as append(): sort() changes the list and gives back None. Use marks.sort() on its own line, or marks = sorted(marks).

Avoid: mixing numbers and text

PYTHONedit me
items = [3, "two", 1]
items.sort()
OUTPUT
TypeError: '<' not supported between instances of 'str' and 'int'

Python can't say whether "two" is smaller than 3, so it stops. Sort lists that hold one type.

list.sort() sorts the list itself. sorted(list) gives a new sorted list and leaves the old one alone.

your turnType the output

Type what this prints

nums = [3, 1, 2] result = nums.sort() print(result)
Read the code line by line, then type the output exactly.

min(), max() and sum() of a List

Give a list of numbers to min(), max() or sum(), and you get the smallest item, the largest item, or all the items added up.

Think of a teacher with a sheet of marks. In one glance they want the top mark, the lowest mark and the total. These three functions do that for you.

PYTHONedit me
marks = [72, 95, 60, 88]
print(min(marks))
print(max(marks))
print(sum(marks))
OUTPUT
60
95
315

The average

The average is the total divided by the number of items. You already know both parts: sum() and len(). Round it with :.2f in an f-string from chapter 5:

PYTHONedit me
marks = [72, 95, 60, 88, 71]
average = sum(marks) / len(marks)
print(f"Average: {average:.2f}")
OUTPUT
Average: 77.20

The rules

  • sum() works only with numbers.
  • min() and max() also work with strings. They use alphabet order, like sorted().
  • sum([]) is 0, but min([]) and max([]) give a ValueError: an empty list has no smallest item.
PYTHONedit me
names = ["Rocky", "Sunny", "Lucky"]
print(min(names))
print(max(names))
OUTPUT
Lucky
Sunny

Avoid: numbers stored as text

PYTHONedit me
marks = ["72", "95"]
print(sum(marks))
OUTPUT
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The quotes make the marks strings, and Python can't add text to a number. This happens when you store input() without int().

Good: convert as you store: marks = [int(input()), int(input())].

min() and max() find the smallest and largest item. sum() adds them all up.

your turnFill the gap

Print the lowest temperature

temps = [31, 28, 35, 30] print(?(temps))

It should print: 28

Which piece makes this code work?

count() and index(): How Many and Where

Two more methods search a list for you. count() tells you how many times a value appears. index() tells you the index where it first appears.

Think of counting votes after a class election: how many votes did "yes" get, and who voted first?

PYTHONedit me
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"))
print(votes.count("maybe"))
print(votes.index("no"))
OUTPUT
3
0
1

The rules

  • list.count(value) gives a whole number. A missing value gives 0, with no error.
  • list.index(value) gives the index of the first match.
  • A missing value in index() is a ValueError, like remove().
PYTHONedit me
votes = ["yes", "no"]
print(votes.index("maybe"))
OUTPUT
ValueError: list.index(x): x not in list

Good: check with in first

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
name = input()
if name in friends:
    print(f"{name} is at index {friends.index(name)}")
else:
    print(f"{name} is not in the list")
OUTPUT
Lucky is at index 2

All the list tools in one table

You writeYou get
x in itemsTrue or False
items.sort() / sorted(items)the list sorted / a new sorted list
min(items) / max(items)the smallest / largest item
sum(items)all the numbers added up
items.count(x)how many times x appears
items.index(x)where x first appears

count() tells you how many times a value appears. index() tells you where it first appears.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

age = int(input()) print(age + 1)

The user types: 17

Your turn! What will this code show on the screen?

Practice: List tools

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 78.Python Program to Check If an Item Is on the MenuEasySolve
  2. 79.Python Program to Make a Class Marks ReportHardSolve