alt text

Table of contents
  1. Advanced Tuples
    1. Using Parentheses with Tuples
      1. Interpolating Values in a String
    2. Creating Single-Item Tuples
    3. Using the tuple() Constructor
      1. Examples:
    4. Accessing Items in a Tuple: Indexing
      1. Example:
      2. Example:
    5. Retrieving Multiple Items From a Tuple: Slicing
      1. Example:
    6. Exploring Tuple Immutability
      1. Example:
    7. Packing and Unpacking Tuples
      1. Example:
    8. Returning Tuples From Functions
      1. Example:
    9. Concatenating and Repeating Tuples
      1. Concatenating Tuples
      2. Repeating Tuples
    10. Reversing and Sorting Tuples
      1. Reversing a Tuple
      2. Sorting a Tuple
    11. Traversing Tuples in Python
      1. Using a for Loop
      2. Using a List Comprehension
    12. Other Features of Tuples
      1. .count() and .index() Methods
      2. Membership Tests
      3. Getting the Length of a Tuple
      4. Comparing Tuples
      5. Common Traps

Advanced Tuples

In this article, we’ll explore some advanced features and uses of tuples in Python.

Using Parentheses with Tuples

Interpolating Values in a String

When using the % operator to insert values into a string, you need to wrap the values in a tuple using parentheses.

# Correct way
print("Hi, %s! You are %s years old." % ("Ravi", 30))
# Output: 'Hi, Ravi! You are 30 years old.'

# Incorrect way
print("Hi, %s! You are %s years old." % "Ravi", 30)
# Output: TypeError: not enough arguments for format string

In the first example, the values are wrapped in a tuple, so it works. The second example raises an error because the values are not in a tuple.

Creating Single-Item Tuples

To make a tuple with only one item, you need to include a comma after the item.

one_word = "Pranam",
print(one_word)  # Output: ('Pranam',)

one_number = (88,)
print(one_number)  # Output: (88,)

The comma is necessary to make it a tuple and not just a regular string or number.

Using the tuple() Constructor

You can use the tuple() function to make tuples from a list, set, dictionary, or string. If you call tuple() without any arguments, it creates an empty tuple.

Examples:

print(tuple(["Asharam Bapu", 28, 5.9, "India"]))
# Output: ('Asharam Bapu', 28, 5.9, 'India')

print(tuple("Developer"))
# Output: ('D', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r')

print(tuple({
    "make": "Honda",
    "model": "Civic",
    "year": 2021,
}.values()))
# Output: ('Honda', 'Civic', 2021)

print(tuple())
# Output: ()

Accessing Items in a Tuple: Indexing

You can get items from a tuple using their index numbers. Indexes start from 0.

Example:

person = ("Sita", 22, 5.4, "Nepal")
print(person[0])  # Output: 'Sita'
print(person[1])  # Output: 22
print(person[3])  # Output: 'Nepal'

You can also use negative indexes to get items from the end.

Example:

print(person[-1])  # Output: 'Nepal'
print(person[-2])  # Output: 5.4

Retrieving Multiple Items From a Tuple: Slicing

Slicing allows you to get parts of a tuple.

Example:

days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(days[:3])  # Output: ('Sunday', 'Monday', 'Tuesday')
print(days[3:])  # Output: ('Wednesday', 'Thursday', 'Friday', 'Saturday')

Exploring Tuple Immutability

Tuples are immutable, which means you can’t change, add, or remove items after creating them.

Example:

person = ("Sita", 22, 5.4, "Nepal")
# Trying to change a value will cause an error
person[3] = "India"
# Output: TypeError: 'tuple' object does not support item assignment

# Trying to delete an item will cause an error
del person[2]
# Output: TypeError: 'tuple' object doesn't support item deletion

Packing and Unpacking Tuples

Example:

# Packing a tuple
coordinates = (19.0760, 72.8777)

# Unpacking a tuple
lat, lon = coordinates
print(lat)  # Output: 19.0760
print(lon)  # Output: 72.8777

Returning Tuples From Functions

Functions can return multiple values as tuples.

Example:

def min_max(values):
    if not values:
        raise ValueError("input list must not be empty")
    return min(values), max(values)

result = min_max([7, 2, 8, 4, 5])
print(result)  # Output: (2, 8)
print(type(result))  # Output: <class 'tuple'>

Concatenating and Repeating Tuples

Concatenating Tuples

name = ("Rohit",)
surname = ("Sharma",)
full_name = name + surname
print(full_name)
# Output: ('Rohit', 'Sharma')

Repeating Tuples

numbers = (1, 2, 3)
print(numbers * 2)
# Output: (1, 2, 3, 1, 2, 3)

Reversing and Sorting Tuples

Reversing a Tuple

days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
reversed_days = days[::-1]
print(reversed_days)
# Output: ('Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday', 'Sunday')

Sorting a Tuple

ages = (45, 23, 67, 12, 34)
print(sorted(ages))
# Output: [12, 23, 34, 45, 67]

Traversing Tuples in Python

Using a for Loop

monthly_sales = (
    ("January", 12000),
    ("February", 14000),
    ("March", 13000),
    ("April", 15000),
)

total_sales = 0
for month, sales in monthly_sales:
    total_sales += sales

print(total_sales)  # Output: 54000

Using a List Comprehension

numbers = ("10", "20", "30")
print(tuple(int(num) for num in numbers))
# Output: (10, 20, 30)

Other Features of Tuples

.count() and .index() Methods

fruits = ("mango", "banana", "apple", "mango", "mango", "kiwi", "banana")
print(fruits.count("mango"))  # Output: 3
print(fruits.index("kiwi"))  # Output: 5

Membership Tests

languages = ("Hindi", "English", "Tamil", "Telugu")
print("Tamil" in languages)  # Output: True
print("Bengali" not in languages)  # Output: True

Getting the Length of a Tuple

details = ("Rajesh", "Teacher", "Delhi", 45)
print(len(details))  # Output: 4

Comparing Tuples

print((3, 4) == (3, 4))  # Output: True
print((10, 15, 20) < (20, 15, 10))  # Output: True
print((7, 8, 9) <= (7, 8, 9))  # Output: True

Common Traps

When creating a one-item tuple, don’t forget the trailing comma.

items = (99,)
print(type(items))  # Output: <class 'tuple'>

Tuples containing mutable objects, like lists, can’t be used as dictionary keys.

# This will raise an error
cities_info = {
    ("Mumbai", [18.975, 72.8258]): "Financial Capital",
}
# Output: TypeError: unhashable type: 'list'