-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path06_tuples.py
More file actions
48 lines (32 loc) · 1.27 KB
/
06_tuples.py
File metadata and controls
48 lines (32 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Python tuples are sort of like lists, except they're immutable and
are usually used to hold heterogenous data, as opposed to lists
which are typically used to hold homogenous data. Tuples use
parens instead of square brackets.
More specifically, tuples are faster than lists. If you're looking
to just define a constant set of values and that set of values
never needs to be mutated, use a tuple instead of a list.
Additionally, your code will be safer if you opt to "write-protect"
data that does not need to be changed. Tuples enforce immutability
automatically.
"""
# Example:
import math
def dist(a, b):
"""Compute the distance between two x,y points."""
x0, y0 = a # Destructuring assignment
x1, y1 = b
return math.sqrt((x1 - x0)**2 + (y1 - y0)**2)
a = (2, 7) # <-- x,y coordinates stored in tuples
b = (-14, 72)
# Prints "Distance is 66.94"
print("Distance is: {:.2f}".format(dist(a, b)))
# Write a function `print_tuple` that prints all the values in a tuple
def print_tuple(tuple):
for number in tuple:
print(number)
t = (1, 2, 5, 7, 99)
print_tuple(t) # Prints 1 2 5 7 99, one per line
# Declare a tuple of 1 element then print it
u = (1) # What needs to be added to make this work? / Answer: int needs to be cast as str
print_tuple(str(u))