Every topic starts at New. Sign in and your practice counts.
Some sets of values must remain in order and unchanging throughout a program. This topic introduces tuples for that fixed storage in Python.
This topic teaches what makes a tuple immutable and ordered and how to read values with indexing, membership tests and counting and how to build new tuples by concatenation.
Some sets of values must remain in order and unchanging throughout the program. Tuples provide that fixed storage in Python.
In Python, a tuple is written with round brackets in the form (,,_). It is a special type of list that is immutable, so its contents cannot be updated once it has been created. The objects and their arrangement can be viewed, but values cannot be added, removed or rearranged.
Tuples are used when a set of values must remain in order and unchanging throughout the program. Days of the week, such as ("Monday", "Tuesday", "Wednesday"), and geographical coordinates of latitude and longitude are examples where order must stay fixed.
A tuple of student grades can contain duplicate values, and printing it shows those duplicates. Individual grades are accessed by specifying the index, which starts from 0. For example, grades[0] gives the first grade and grades[2] gives the third grade. The in operator checks whether a specific grade exists in the tuple, and the count() method returns the number of times a specific value appears in the tuple.
The following program creates a grades tuple and applies indexing, membership testing, counting and concatenation.
grades = (85, 92, 78, 92, 85, 95)
print(grades)
print("First grade:", grades[0])
print("Third grade:", grades[2])
if 92 in grades:
print("Student got 92")
print(grades.count(92))
new_grades = grades + (88, 90)
print(new_grades)
In the example, the test for 92 succeeds, so the program reports that the student got 92. Counting 92 returns 2 because 92 appears twice in the tuple.
An existing tuple cannot be changed in place. A new tuple is created by concatenating existing tuples with the + operator. Joining grades with (88, 90) creates new_grades without changing the original tuple.