Tuples and tuple() in Python

Overview

In Python a tuple is a type of data structure that holds items together. It functions like a list. The key difference is that tuples cannot be changed once they are created because they are immutable. Tuples are distinguished by their use of parentheses of the brackets used for lists. Even though tuples cannot be altered they are popular, in Python for their benefits, such as being usable as keys, in dictionaries and working well with functions that need to return values.

Why Use Tuples in Python?

Tuples, a data type in Python enable the storage of multiple items within one variable. They remain unchanged once created due to their immutability. Tuples are formed by enclosing items, in parentheses and separating them with commas. Below is an illustration of how to create a tuple.

my_tuple = (1, "apple", True)

Tuples prove handy in Python for reasons. Firstly they serve to group related information together. For instance a tuple can depict a point on a two plane with the first value representing the x coordinate and the second value representing the y coordinate.

Moreover tuples offer the advantage of maintaining data integrity by preventing modifications to the values within a collection. This immutability feature is particularly valuable when dealing with crucial data.

Additionally tuples can function as keys in dictionaries to their immutable nature unlike lists that cannot serve as dictionary keys despite resembling tuples. This attribute makes tuples suitable, for scenarios requiring identification or indexing.

How Are Tuples Different from Lists?

Tuples and lists play roles as data structures in Python but they have distinct characteristics. One key difference lies in their immutability and handling of lengths. Tuples being immutable cannot be changed once created whereas lists can be freely modified.

This property makes tuples ideal for storing data like coordinates or database records while lists are better for situations where elements need to be altered dynamically. In terms of length tuples have a fixed number of elements that cannot be adjusted whereas lists can grow or shrink as needed. This flexibility makes lists suitable for managing data that may vary in size or require updates.

Moreover tuples typically use memory efficiently than lists due to their immutability. List operations can be prone, to errors when dealing with threads because of their mutable nature leading to potential race conditions. In contrast tuple operations are safer since they are immutable and thus thread safe.

Creating Tuples

Using Literal Syntax

In Python you can make tuples using a series of objects separated by commas. When creating a tuple with syntax just list the objects you want in the tuple separated by commas. For instance if you want a tuple, with the numbers 1, 2 and 3 you can write it like this.

(1, 2, 3)

It's not necessary to use parentheses around the values separated by commas. Its a good idea, for better readability.

Using the tuple() Constructor

The tuple() function in Python is a tool that allows us to form tuples from various types of objects that can be iterated over. These objects can range from sets, lists, strings to even generator expressions. When we use the tuple() function with an object as input it generates a new tuple containing the same elements, as the original object. If we call tuple() without specifying any argument it results in a tuple being created anew.

Single Item Tuples

To make a tuple with one item remember to include a comma after the item. Otherwise it won't be identified as a tuple. For instance if you want to create a tuple, with the value 5 you should do the following.

(5,)

In Python 3.11 you have the option to form a tuple with one item without requiring a comma at the end by enclosing it in parentheses.

(5)

Empty Tuples

In Python empty tuples refer to tuples that do not have any elements. You can create them by using a set of parentheses (). These empty tuples serve as placeholders or, for setting up a tuple without any starting values.

Accessing Tuple Items

Indexing with Positive Indices

In Python to retrieve elements, from tuples using indices we utilize square brackets. Tuples consist of ordered elements with each element being assigned an index that begins at 0 for the initial element. For instance -

my_tuple = ("apple", "banana", "cherry")
first_item = my_tuple[0]  # Accesses "apple"

Indexing with Negative Indices

Negative indices allow us to access items in a tuple by counting from the end. Negative indexing starts from -1 for the last item. For example:

my_tuple = (10, 20, 30, 40, 50)
last_item = my_tuple[-1]  # Accesses 50

Slicing Tuples

Slicing tuples refers to extracting specific portions of a tuple using the slicing operator. The slicing operator is denoted by the colon : and can be used to specify optional indices: start, stop, and step. For example:

my_tuple = (1, 2, 3, 4, 5)
slice = my_tuple[1:4]  # Returns (2, 3, 4)

Iterating Over a Tuple

To iterate over a tuple using a for loop:

my_tuple = (1, 2, 3)
for item in my_tuple:
    print(item)

Immutable Nature of Tuples

Tuples are unchangeable so once they are created their contents cannot be altered. This lack of flexibility imposes restrictions on adding, deleting and changing items within tuples. For instance you cannot insert an element into a tuple that already exists or delete an element from it. Additionally modifying the value of an item in a tuple is not allowed. This decision, in design ensures security and reliability in situations where maintaining data accuracy and coherence is crucial.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate