Python: Tuples
Besides primitive types, Python has composite data types that store multiple values at once. A university student is described by a name, age, and GPA. A film has a title, release year, and rating. These groups of values are natural to store together.
A tuple is simpler than any other composite type. It stores several values in a strictly defined order. Once created, it cannot be changed.
A tuple works well for data that always belongs together.
student = ('Alice', 20, 4.8) # name, age, GPA
film = ('Inception', 2010, 8.8) # title, year, ratingCreating a tuple
A tuple is written in parentheses with values separated by commas.
point = (10, 20)
colors = ('red', 'green', 'blue')
mixed = (42, 'hello', 3.14)A single-element tuple requires a trailing comma. Without it, Python treats the parentheses as grouping an expression.
single = (42,) # a tuple with one element
not_tuple = (42) # just the number 42The parentheses are optional. Python recognizes a tuple by the commas.
point = 10, 20
print(type(point)) # => <class 'tuple'>Accessing elements
Tuple elements are numbered from zero. They are accessed by index.
point = (10, 20)
print(point[0]) # => 10
print(point[1]) # => 20Tuples are immutable
A tuple cannot be modified after creation. Attempting to replace an element raises an error.
point = (10, 20)
point[0] = 5 # TypeError: 'tuple' object does not support item assignmentImmutability is built into tuples deliberately. No matter where a tuple is passed, its data stays the same.
Unpacking
Tuple elements can be assigned to multiple variables at once.
point = (10, 20)
x, y = point
print(x) # => 10
print(y) # => 20Python matches values to variables in order. The number of variables must equal the number of elements.
Instructions
Two cities lie on the same road. Each is described by a tuple with a name and a position in kilometers from the start of the route:
city_a = ('Moscow', 10)
city_b = ('Saint Petersburg', 644)Calculate the distance between the cities and print the result in this format:
From: Moscow
To: Saint Petersburg
Distance: 634 kmTips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Your exercise will be checked with these tests:
import runpy
def test(capsys):
expected = """From: Moscow
To: Saint Petersburg
Distance: 634 km"""
runpy.run_module('solution')
out, _ = capsys.readouterr()
assert out.strip() == expectedTeacher's solution will be available in:
20:00
