Tuples are similar to lists because they store ordered values. The difference is that tuples cannot be modified after creation.
Tuples
Tuples use parentheses (). A one-element tuple must include a trailing comma.
point = (3, 4)
single = (8,)
print(point[0])
print(point[1])Tuples are useful for data that should not be casually changed, such as coordinates, dates, or color values.
Distance between points
import math
p1 = (0, 0)
p2 = (3, 4)
distance = math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
print("Distance: %.1f" % distance)Output:
Distance: 5.0KNOWLEDGE QUIZ
QUESTION
How should a one-element tuple be written?
Sequence statistics
Many built-in functions can work directly on sequences:
len(): length.max(): maximum value.min(): minimum value.sum(): total.any(): true if at least one element is true.all(): true only when all elements are true.
lst = [4, 0, 1, 3, 2]
tup = (8, 5, 7, 9)
print(len(lst))
print(len(tup))
print(max(lst))
print(min(tup))
print(sum(lst))
print(sum(tup))any() and all() are useful for checking groups of conditions.
scores = [85, 92, 78]
print(all(score >= 60 for score in scores))
print(any(score >= 90 for score in scores))INTERACTIVE LAB
Truth control room: any() versus all()
ACCESSFREE
Click each condition to toggle it. any() needs one green light; all() needs every light.
any(values)false
all(values)false
KNOWLEDGE QUIZ
QUESTION
What is all([True, True, False])?
HANDS-ON PRACTICE
Find the point closest to the origin
Given a list of coordinate tuples, compute each distance to the origin and find the closest point.
- Prepare points containing (x, y) tuples.
- Compute each distance to the origin.
- Print the point with the smallest distance.