11.1 Determining the Number of Elements in a Tuple
Tuples are immutable sequences that can contain different data types. Using
the built-in function len()
for a tuple lets you find out the number of elements in it. Let's start with that.
Example of using the len()
function with a tuple:
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # Outputs 5
You can pass either a variable containing a tuple or the tuple itself directly to the len()
function. Examples:
print(len(())) # Outputs 0
print(len((1, 2, 3))) # Outputs 3
print(len(((1, 2, 3),))) # Outputs 1
If you don't count unpacking the tuple, determining the number of its elements is the most common operation with a tuple 😊
11.2 Tuple Type
Using the type()
function when working with tuples allows you to determine if a variable is a tuple, which is especially important in the context of dynamic typing in Python.
Example:
my_tuple = (1, 2, 3)
print(type(my_tuple)) # Outputs <class 'tuple'>
Checking that a variable contains the desired type looks like this:
my_tuple = (1, 2.5, 'string', [3, 4])
if type(my_tuple) == tuple:
print("Tuple!") # Outputs: Tuple!
11.3 Accessing an Element
Accessing elements of a tuple is done through indexing, similar to lists. Tuples are ordered and immutable collections, allowing you to access elements by their index.
Important!
Indexes start at zero, so
the first element of a tuple has index 0, the second has index 1, and so on. Python also
supports negative indexes, where -1 refers to the last element
of the tuple, -2 to the second-to-last, and so on.
To refer to a specific element of a tuple, use square brackets with the element's index. The general form of this operation looks like:
tuple[index]
Example:
my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[1]) # Outputs 'banana'
print(my_tuple[2]) # Outputs 'cherry'
Just like with lists, tuples support negative indexes.
Accessing the last element of a tuple:
my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[-1]) # Outputs 'cherry'
Accessing the second-to-last element of a tuple:
my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[-2]) # Outputs 'banana'
GO TO FULL VERSION