Python, lesson 7
One variable holds one value. Most real data comes in groups: the scores in a game, the items in a basket, the phone numbers in a contact list. Python's built-in collections hold many values under one name.
A list is an ordered sequence you can change. Write it with square brackets:
Some other everyday operations:
Reading past the end, like scores[99], raises IndexError. Slices are forgiving and just
return fewer items.
sorted(scores) returns a new sorted list and leaves the original alone, while
scores.sort() sorts the list in place and returns None. Add reverse=True to either
to sort from largest to smallest. sum(), and work on any list of numbers.
2 exercises to try what you just read.
min()max()You can build a list from a line of input in one go:
That bracketed form is a list comprehension; lesson 14 covers it properly. For now, read it
as "an int for every part of the line".
A tuple is like a list that can't be changed after it's made. Write it with parentheses (or just commas). Tuples suit small, fixed groups such as a coordinate or a name with a score:
A dictionary (dict) maps keys to values. You look values up by key instead of by
position, which is ideal for anything that has a name:
Looking up a missing key with square brackets raises KeyError, which is why .get() with a
default is so handy. Keys must be immutable values such as strings, numbers or tuples.
Dictionaries remember the order in which keys were inserted.
enumerate() gives you a counter alongside each item, and .items() gives you each key with
its value. Both save you from juggling index variables by hand.
One line of input holds the race scores, separated by spaces (at least one score). Print the best three scores from highest to lowest on one line, separated by single spaces. If there are fewer than three scores, print all of them.
Sample input:
Sample output:
The first line is a number n. The next n lines each hold a name and a phone number
separated by a space. Every line after that is a name to look up. For each lookup print the
number, or not found if the name isn't in the book. If a name is listed twice, the later
number replaces the earlier one.
Sample input:
Sample output:
scores = [72, 95, 88]
scores.append(60) # add to the end -> [72, 95, 88, 60]
print(scores[0]) # 72 (indexes start at 0)
print(scores[-1]) # 60 (negative indexes count from the end)
print(len(scores)) # 4scores.insert(0, 100) # put 100 at the front
scores.remove(88) # remove the first 88
last = scores.pop() # remove and return the last item
print(95 in scores) # True: membership test
print(scores[1:3]) # a slice: items at index 1 and 2, as a new listnumbers = [int(part) for part in input().split()]point = (3, 4)
x, y = point # unpackingprices = {"tea": 2.5, "cake": 3.0}
prices["juice"] = 2.0 # add or overwrite
print(prices["tea"]) # 2.5
print("milk" in prices) # False: checks keys
print(prices.get("milk", 0)) # 0: a default instead of an error
del prices["cake"]for score in scores:
print(score)
for position, score in enumerate(scores, start=1):
print(position, score)
for item, price in prices.items():
print(f"{item}: {price}")72 95 88 60 9195 91 882
ana 555-1234
ben 555-9876
ben
cara555-9876
not found