1. Tuple basics
A tuple is an ordered collection of values that cannot be changed after it is created. You write one with parentheses and commas:
The parentheses are optional; the comma is what creates the tuple. point = 3, 5 is the same tuple.
A one-element tuple needs a trailing comma: (42,) is a tuple, while (42) is just the number 42.
Tuples use the same indexes and slices as lists and strings:
len(tuple) returns how many elements it has. When you print a tuple, Python shows it with parentheses and strings with single quotes: ('a', 'b', 'c'). Tuples are useful for fixed groups of values, such as a coordinate or an RGB color.
A tuple and a list look alike: both keep their order, use indexes and slices, and work with len(). The difference is what you can do after creating them:
List [...] | Tuple (...) | |
|---|---|---|
| Read by index | Yes | Yes |
| Replace an element | Yes | No |
| Add or remove elements | Yes | No |
Use a list when the data will grow or change, and a tuple when the group is fixed. [3, 5] is a point you can move later; (3, 5) is one fixed position.
Coming from JavaScript? A tuple is like a fixed array, or a TypeScript readonly [number, number]. The trailing comma matters: (42,) is a one-element tuple, while (42) is just a number.
Print a tuple
A tuple is written with parentheses and commas. Create point with the values 3 and 5 using a tuple literal, then print the whole tuple.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a tuple element
Indexes start at 0. Print the element at index 1 of point, where point = ("red", "green", "blue").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Length of a tuple
len(tuple) returns how many elements a tuple has. Print the length of ("a", "b", "c", "d").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Slice a tuple
A slice tuple[start:stop] returns a new tuple with the elements from start up to, but not including, stop. Print the slice from index 1 to index 3 of letters, where letters = ("a", "b", "c", "d").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A tuple with one element
A trailing comma makes a one-element tuple: (42,). Without it, (42) is just the number 42. Create single with one element, the number 42, using a tuple literal. Print it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.