Tuples in Python
Overview
Tuples are one of the four built-in data types in Python used to store collections of data. They are similar to lists but have a crucial difference: tuples are immutable. This lesson will cover how to create, access, and use tuples, as well as their advantages and limitations.
Introduction
A tuple is a collection which is ordered and immutable. Tuples are written with round brackets ()
and can contain items of different data types.
Creating Tuples
- Syntax:
(item1, item2, item3,...)
- Example:
my_tuple = (1, "Hello", 3.4)
Accessing Tuple Items
- Indexing: Access items by referring to the index number, e.g.,
my_tuple[1]
would return"Hello"
. - Negative Indexing: Access items from the end, e.g.,
my_tuple[-1]
would return3.4
. - Slicing: Access a range of items, e.g.,
my_tuple[0:2]
would return(1, "Hello")
.
Immutability of Tuples
Once a tuple is created, you cannot change its values. Adding, removing, or modifying elements in a tuple is not allowed. This immutability can serve as an assurance that data remains constant throughout the program.
Tuple Operations
- Concatenation: Combine tuples using
+
, e.g.,(1, 2) + (3, 4)
results in(1, 2, 3, 4)
. - Repetition: Repeat tuples using
*
, e.g.,('Repeat',) * 3
results in('Repeat', 'Repeat', 'Repeat')
. - Membership Test: Use
in
to check if an item exists in a tuple, e.g.,2 in (1, 2, 3)
returnsTrue
.
Tuple Methods
Tuples have fewer built-in methods compared to lists, due to their immutability. The two primary ones are:
count(x)
: Returns the number of timesx
appears in the tuple.index(x)
: Returns the index of the first occurrence ofx
in the tuple.
Why Use Tuples?
- Performance: Tuples can be slightly faster than lists for constant sets of values.
- Safety: Use tuples for write-protected data to ensure that data cannot be modified.
- Return Multiple Values: Functions can use tuples to return multiple values.
Tuples vs Lists
- Syntax: Lists use
[]
, tuples use()
. - Mutability: Lists are mutable; tuples are immutable.
- Usage: Tuples are generally used for heterogeneous (different) data types and lists for homogeneous (similar) data types.
Conclusion
Tuples are a fundamental data structure in Python that offer a way to store a collection of items in an ordered and immutable manner. They are particularly useful when you need to ensure that data cannot be changed or when returning multiple values from a function.