4.2 Tuples and Sequence Statistics
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.
python
point = (3, 4)
single = (8,)
print(point[0]) # 3
print(point[1]) # 4Tuples are useful for data that should not be casually changed, such as coordinates, dates, or color values.
Distance between points
python
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:
text
Distance: 5.0Loading concept check...
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.
python
lst = [4, 0, 1, 3, 2]
tup = (8, 5, 7, 9)
print(len(lst)) # 5
print(len(tup)) # 4
print(max(lst)) # 4
print(min(tup)) # 5
print(sum(lst)) # 10
print(sum(tup)) # 29any() and all() are useful for checking groups of conditions.
python
scores = [85, 92, 78]
print(all(score >= 60 for score in scores)) # True
print(any(score >= 90 for score in scores)) # TrueLoading concept check...
Loading practice...