Tuples are a fundamental data structure in Python, similar to lists but with a few key differences. They are used to store a collection of items and are immutable, meaning that once a tuple is created, it cannot be changed.
What is a Tuple?
A tuple is a collection of items which are ordered and immutable. In Python, tuples are written with parentheses ()
, and items are separated by commas. Here's an example:
my_tuple = (1, 2, 3, 4, 5)
In the above example, my_tuple
is a tuple containing five integers.
Creating Tuples
You can create a tuple in several ways:
- Using parentheses: As shown in the example above.
- Using the
tuple()
constructor: This is useful if you want to convert a list or another iterable into a tuple.
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
Tuple Elements
Tuples can contain elements of different data types. For example:
my_tuple = (1, "two", 3.0, [4, 5])
In the above tuple, you have an integer, a string, a float, and a list.
Tuple Slicing
Similar to lists, you can slice tuples to get a subset of elements. For example:
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
The sliced_tuple
will be (2, 3, 4)
.
Tuple Indexing
You can also access elements by their index in a tuple. Remember that indexing starts at 0.
my_tuple = (1, 2, 3, 4, 5)
second_element = my_tuple[1]
The second_element
will be 2
.
Tuple Packing and Unpacking
Packing is the process of putting multiple values into a single variable, while unpacking is the opposite process.
Packing:
a, b, c, d, e = 1, 2, 3, 4, 5
Unpacking:
my_tuple = (1, 2, 3, 4, 5)
a, b, *rest = my_tuple
In the unpacking example, a
will be 1
, b
will be 2
, and rest
will be (3, 4, 5)
.
Tuple vs List
While tuples and lists are similar, there are some key differences:
- Immutable: Tuples are immutable, meaning they cannot be changed after creation. Lists are mutable.
- Performance: Tuples are generally faster than lists because they are immutable.
- Use Case: Use tuples when you need an immutable sequence of items, and lists when you need a mutable sequence.
For more information on Python lists, you can read our Python Lists Tutorial.