Skip to content

Python Tuples (Tuple)

Tuples are another very important data sequence type in Python. They are very similar to lists, but with one key difference: tuples are immutable.

What is a Tuple?

A tuple is an ordered and immutable collection. Once created, you cannot modify, add, or delete elements in the tuple.

Creating Tuples

Tuples are defined using parentheses (), with elements separated by commas ,.

python
# Create an empty tuple
empty_tuple = ()

# Tuple containing integers
numbers = (1, 2, 3, 4, 5)

# Tuple containing mixed data types
mixed_tuple = (1, "hello", 3.14, True)

# Can also use tuple() constructor
from_list = tuple([1, 2, 3]) # Create tuple from list

# Parentheses can be omitted when creating
my_tuple = 1, "a", "b" # This is also a tuple
print(my_tuple) # Output: (1, 'a', 'b')

Note: Creating a tuple with only one element

If you want to create a tuple containing only one element, you must add a comma , after that element.

python
single_element_tuple = (42,) # This is a tuple
not_a_tuple = (42)          # This is just the integer 42

print(type(single_element_tuple)) # Output: <class 'tuple'>
print(type(not_a_tuple))          # Output: <class 'int'>

Accessing Tuple Elements

Accessing tuple elements works exactly the same as with lists, through indexing and slicing.

python
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')

print(my_tuple[0])   # Output: 'p'
print(my_tuple[-1])  # Output: 'n'
print(my_tuple[1:4]) # Output: ('y', 't', 'h')

Tuples are Immutable

This is the core difference between tuples and lists. Any attempt to modify a tuple will result in a TypeError.

python
my_tuple = (1, 2, 3)

# The following operations will all raise errors
# my_tuple[0] = 99      # TypeError: 'tuple' object does not support item assignment
# my_tuple.append(4)    # AttributeError: 'tuple' object has no attribute 'append'
# my_tuple.remove(1)    # AttributeError: 'tuple' object has no attribute 'remove'

Why Use Tuples?

Since lists are more feature-rich, why do we need tuples?

  1. Data Integrity: Since tuples are immutable, you can ensure their contents won't be accidentally modified during program execution. This makes code safer and more predictable. Perfect for use as constant collections.

  2. Performance Optimization: In most cases, tuples are slightly faster to process than lists and consume less memory.

  3. Can be Used as Dictionary Keys: Because tuples are immutable (hashable), they can be used as dictionary keys. Lists are mutable and cannot be used as dictionary keys.

    python
    locations = {
        (35.6895, 139.6917): "Tokyo",
        (40.7128, -74.0060): "New York"
    }

Tuple Methods

Because tuples are immutable, they have very few methods - only two:

  • tuple.count(x): Returns the number of times element x appears in the tuple.
  • tuple.index(x): Returns the index of the first occurrence of element x in the tuple.

Tuple Unpacking

This is a very convenient and Pythonic feature that allows you to assign elements of a tuple to multiple variables.

python
# Define a tuple
user_profile = ("John Doe", 30, "john.doe@example.com")

# Unpack
name, age, email = user_profile

print(name)  # Output: John Doe
print(age)   # Output: 30
print(email) # Output: john.doe@example.com

This feature is particularly useful when functions return multiple values, as a function's multiple return values are actually packaged as a tuple and returned.

Content is for learning and research only.