Home » Learn Python » Containers » Python Tuples

Python Tuples

A Python tuple can store an ordered collection of objects, which do not all have to have the same type. The objects remain in the order you put them in. You can access particular objects within the tuple using an index which starts at zero.

Tuples are immutable; you can’t add, change or remove objects in a tuple once you’ve created it.

animals = ("dog", "cat", "horse", "rabbit")

print(animals)

print(animals[0])
print(animals[1])
print(animals[2])
print(animals[3])
('dog', 'cat', 'horse', 'rabbit')
dog
cat
horse
rabbit

Iterating Over Tuples

Since tuples are an iterator, you can iterate over them using a for loop.

animals = ("dog", "cat", "horse", "rabbit")

for animal in animals:
    print(animal)
dog
cat
horse
rabbit

Packing and Unpacking Tuples

When we add values to a tuple, we call this “packing” the tuple.

We can also do the converse: we can “unpack” the tuple, placing the values it contains in separate variables.

# Pack the tuple
animals = ("dog", "cat", "horse", "rabbit")

# Unpack the tuple
(animal1, animal2, animal3, animal4) = animals
print(animal1)
print(animal2)
print(animal3)
print(animal4)
dog
cat
horse
rabbit

In this code, animal1, animal2, animal3 and animal4 are simply variable names that we’ve invented. They can be whatever you like.

Leave a Reply

Blog at WordPress.com.

%d