Introduction to Python Tuples
What are Tuples in Python?
Tuples belong to Python's built-in collection data structures, alongside lists, sets, and dictionaries. They're quite similar to lists, as we can store a collection of elements, but with some notable differences.
First and foremost, tuples use parentheses instead of square brackets to define their elements. Another key difference is that they're immutable, meaning their elements cannot be changed once we define them. They can also contain duplicate elements, as seen in some of the examples in the sections below.
Creating a Tuple
We can create a tuple in several ways. Let's start with the basic syntax and then expand further. Commonly, we assign the tuple to a variable and populate it with elements enclosed in parentheses, like so:
tuple_example = (1, 2, 3)
Technically, we can omit the parentheses in tuples. However, this approach isn't a good practice per se, and we should generally avoid it.
Note: Tuples can be of any data type, as well as contain different ones
tuple_example = (1, "hello", 3.14, True)
print(type(tuple_example[0])) # Output: <class 'int'>
print(type(tuple_example[1])) # Output: <class 'str'>
print(type(tuple_example[2])) # Output: <class 'float'>
print(type(tuple_example[3])) # Output: <class 'bool'>
Another approach we can do is to refer to the tuple()
constructor. We should be careful here and remember to include double round brackets and avoid being thrown an error.
new_tuple = tuple(("Python", "JavaScript", "C++"))
print(new_tuple)
# Output: ('Python', 'JavaScript', 'C++')
Single-Element Tuples
We also have the option of creating a single-element tuple. But, we need to include a comma after the element to indicate that it's a tuple.
single_element_tuple = (1,)
print(single_element_tuple)
# Output: (1,)
Tuple Unpacking
Basically, the tuples we created above fall under the process called "packing" since we assigned them to a variable. Let's illustrate how we can unpack a tuple, using the following syntax:
unpack_tuple = ("Python", 1991, "Guido van Rossum")
(language, year, creator) = unpack_tuple
print(language) # Output: Python
print(year) # Output: 1991
print(creator) # Output: Guido van Rossum
print(unpack_tuple) # Output ('Python', 1991, 'Guido van Rossum')
Logically, we can leverage this for functions that return multiple values and capture those values by assigning them to separate variables in a single line of code as we did in the example.
Tuple Indexing and Accessing
Just like we did in lists, we can access elements in tuples with square brackets.
Tuples are also zero-indexed; the first item has an index of 0, the second item has an index of 1, and so on.
tuple_example = (1, "pie", 3.14)
print(tuple_example[1]) # Output: pie
Or, we can refer to negative indexing to target the tuple elements from the end.
print(tuple_example[-1]) # Output: 3.14
Additionally, we can also turn to a process called slicing and extract a sub-section of the tuple elements.
tuple_example = (1, "pie", 3.14, True)
print(tuple_example[1:3]) # Output: ('pie', 3.14)
With the range approach, we get a new tuple containing our "slice". Bear in mind, that we used 3 instead of 2 in the second index, since we start at index 1 which is included, and end at index 2 which is not.
Changing Tuples
Even though tuples are immutable, there are ways to circumvent this and change their contents.
Converting a Tuple to a List
Our first option is to convert them to a list, modify the list with its available Python methods, and then convert it back to a tuple. For clarity, we'll use the basic tuple example we covered at the beginning.
tuple_example = (1, 2, 3)
my_list = list(tuple_example)
my_list.append(4)
tuple_example = tuple(my_list)
print(tuple_example) # Output: (1, 2, 3, 4)
Combining Tuples
Depending on our needs, there are several ways to combine tuples. Let's demonstrate some of them in the sections below.
Concatenating Tuples
We can concatenate two tuples by simply adding them together.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(tuple3) # Output: (1, 2, 3, 4, 5, 6)
Tuples with Duplicate Items
Intriguingly enough, tuples can have duplicates i.e. it's possible for them to contain multiple occurrences of an identical element.
tuple_example = (1, 2, 2, 3)
print(tuple_example) # Output: (1, 2, 2, 3)
Nested Tuples
Finally, it's also possible to have tuples within tuples, known as nested tuples:
nested_tuple = (1, (2, 3), 4)
print(nested_tuple) # Output: (1, (2, 3), 4)
Tuple Methods
We should mention a few methods that are specific to this data structure.
With the count()
we can find out how many times an element occurs in the tuple.
breakfast = ("waffles", "syrup", "bacon", "eggs", "syrup")
print(breakfast.count("syrup")) # Output: 2
Furthermore, with the index()
method we can locate the index where the element occurs for the first time in the tuple.
pets = ("dog", "cat", "bird", "dog", "fish")
print(pets.index("dog")) # Output: 0
Why use Tuples instead of Lists?
So, why use tuples instead of lists?
First and foremost, tuples are slightly faster than lists in terms of performance, especially when dealing with large collections of data. However, this is negligible in most real-world applications and only becomes noticeable with extremely large datasets.
Another key advantage of tuples is that they are immutable, making them ideal for storing data that should not be altered, such as dates, times, or constant values.
Last but not least, tuples are often preferred over lists when we work with dictionaries, as they can be used as keys inside them, while lists cannot. Tuple elements are hashable, meaning that their elements can be used to calculate a unique hash value, while lists are mutable and cannot be hashed.
For more info on tuples and data structures, be sure to check out our additional resources below.