Chapter 3
Transforming and Combining Data
Meet Tuples
Chapter 2 focused on making
You already know
Write a tuple
Most often, you write the items between parentheses and separate them with commas:
Python reports the type as tuple. This tuple contains three items: a learner name, a score, and a total. Tuple items can have different
The commas create the tuple
The parentheses make a tuple easy to recognize, but the commas are what actually create it. In many places, the parentheses are optional:
Python treats point as the tuple (10, 2).
The same rule applies when a function returns comma-separated values:
def position():
x = 10
y = 2
return x, y
return x, y returns one (10, 2).
Parentheses are still helpful, so this course usually includes them when creating a tuple directly. They make the start and end of the group clear.
The comma becomes especially important for a tuple with one item:
one_number = (10,)
not_a_tuple = (10)
one_number is a tuple because of the comma. not_a_tuple is just the integer 10 between grouping parentheses.
Like a list, a tuple keeps its items in order. 0 refers to the first item:
result = ("Mina", 8, 10)
print(result[0])
print(result[1])
print(len(result))
This prints the learner name, the score, and the number of items.
Use a tuple for a fixed group
A list is useful when you may add, remove, or replace items. A tuple is
For example, this
result[1] = 9
Python raises result is a tuple. To represent a different result, create a new tuple:
updated_result = ("Mina", 9, 10)
That fixed shape makes a tuple useful for a small group whose positions have an agreed meaning:
coordinates = (4, 7)
color = (120, 80, 200)
result = ("Mina", 8, 10)
Do not replace every list or dictionary with a tuple. Use a list for a collection that grows or changes. Use a dictionary when labels such as "learner" and "score" need to remain visible. A tuple is most useful when the group is small, ordered, and fixed.
A function can return one tuple
A function always returns one value at a time. That value can itself be a tuple containing several related items. Here, parentheses make the returned group easy to see:
def result_values(attempt):
return (
attempt["learner"],
attempt["score"],
attempt["total"],
)
One
attempt = {"learner": "Mina", "score": 8, "total": 10}
result = result_values(attempt)
result now refers to one tuple with three items.
As the earlier position example showed, the function could omit the parentheses and return comma-separated values directly. The result would still be one tuple.
Which value is a tuple containing a learner, score, and total?
Explore a tuple in the REPL
Use the REPL beside the lesson to create result = ("Mina", 8, 10). Then enter result, type(result), len(result), and each of its three indexed items one at a time.
The next lesson keeps the same result tuple but gives its positions descriptive names instead of repeatedly using result[0], result[1], and result[2].