Page Content

Tutorials

How To Use Tuples In Python With Examples

Tuples In Python

Tuples In Python
Tuples In Python

Lists and tuples are two of Python’s built-in higher-level data structures, but they differ significantly. Being a series, they have ordered elements that may be accessed using an integer index, with the first element being 0 in this case.

Because lists are mutable and tuples are immutable, this is the primary difference between the two types of data. Accordingly, you are unable to add, remove, or swap out elements in a tuple once it has been generated. Consider tuples to be similar to a page that can only be read. For data that shouldn’t change, like coordinates or database entries, their immutability makes them helpful.

Creating Tuples

Tuples can be created in several ways:

Using Parentheses () and Commas: This is the most used method. To make tuples look neater and easier to understand, they are typically defined with brackets. Using only empty brackets (), an empty tuple is produced.

Without Parentheses (Tuple Packing): You can just use commas to separate values to form a tuple. It’s called tuple packing. Although brackets are not required, their use is recommended as it improves readability, particularly in complex expressions or nested tuples.

Single-Item Tuples: A trailing comma must be placed after the element in order to generate a tuple with only one element. The value is simply interpreted by Python as the element enclosed in parenthesis, not as a tuple, if the comma is removed.

Using the tuple() Constructor: A new tuple can be created from an iterable object (such as a list, string, or range) by using the built-in tuple() function.

Accessing Elements

Similar to lists, you use the index of each individual element in a tuple enclosed in square brackets [] to retrieve it. Indices for the first element begin at 0. When a tuple has a negative index, the last element is denoted by -1.

my tuple = ('a', 'b', 'c', 'd', 'e')
# Accessing the first element (index 0)
first element = my tuple
print(f" First element: {first element}") 
# Accessing the third element (index 2)
third element = my tuple
print(f" Third element: {third element}") 
# Accessing the last element (index -1)
last element = my tuple
print(f" Last element: {last element}")

Slicing is another way to access a variety of aspects. A subset of the original elements are included in the new tuple that is produced by slicing. The syntax is [start:end:step], which is comparable to strings and lists.

numbers = (10, 20, 30, 40, 50, 60, 70, 80, 90)
# Get elements from index 1 up to (but not including) index 4
subset tuple = numbers
print(f" Slice [1:4]: {subset tuple}") 
# Get elements from the beginning up to (but not including) index 3
subset tuple = numbers
print(f" Slice [:3]: {subset tuple}") 
# Get elements from index 5 to the end
subset tuple = numbers[5:]
print(f" Slice [5:]: {subset tuple}") 
# Get a copy of the whole tuple using slicing
copy tuple = numbers
print(f" Slice [:]: {copy tuple}") 
# Get elements with a step of 2
subset tuple = numbers
print(f" Slice [::2]: {subset tuple}") 
# Reverse the tuple using slicing with a step of -1
reversed tuple = numbers
print(f" Slice [::-1] (reversed): {reversed 
tuple}") 
Because tuples are immutable, you cannot use 

Tuples are immutable, therefore you can’t alter their elements via indexing or slicing on the left side of an assignment statement. If you attempt to do so, a TypeError will appear.

# Attempting to change an element (will cause an error)
my tuple 
# my tuple = 5 # This line would cause a TypeError
# print(my tuple)

It is possible to alter the mutable object itself, though, if a tuple contains one (such as a list).

Tuple Assignment (Unpacking)

Tuple assignment or unpacking is a special feature of Python. Assigning multiple variables simultaneously from the elements of a sequence (such as a list or tuple) is made possible by this. The assignment must have the same number of variables on the left as there are elements in the tuple on the right.

# Tuple assignment (unpacking)
coordinates 
x, y = coordinates # The tuple (4.21, 9.29) is unpacked into x and y 
print(f" x: {x}")  
print(f" y: {y}") 
# Another example with different types
person data = ("Alice", 30, True)
name, age, is student = person data
print(f" Name: {name}, Age: {age}, Is student: {is student}") # Output: Name: Alice, Age: 30, Is student: True

To access items by index, Python approximately converts tuple assignments like x, y = tuple name into x = tuple name and y = tuple name.

Tuples as Return Values

In Python, a function is only technically able to return one value. On the other hand, a function can efficiently return several related values by packing them into a tuple and then returning that tuple. To allocate the returned data to distinct variables, tuple unpacking is frequently utilized on the caller side.

# Function returning a tuple
def get stats(numbers):
    Calculates and returns the sum and average of a list of numbers.
    total = sum(numbers) # Non-source information: using built-in sum()
    average = total / len(numbers) if len(numbers) > 0 else 0 # Non-source information: calculating average, handling empty list
    return (total, average) 
# Call the function and unpack the returned tuple
data
sum result, avg result = get stats(data) 
print(f" Numbers: {data}")
print(f" Sum: {sum result}") # Output based on calculation: Sum: 100
print(f" Average: {avg result}") # Output based on calculation: Average: 25.0
This pattern is useful when you need to return 

This pattern is helpful when you need to retrieve related data from a function, such a year, month, and day, or a top and lowest score.

Due to their status as sequences, tuples can also be used for other common operations, such as the in operator to check for membership, len() to determine length, count() to determine the number of times a value occurs, index() to get a value’s index, and a for loop. Additionally supported are repetition with * and concatenation with +, however these methods result in new tuples.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.