< All Topics

Python Tuples Data Structure

It is very similar to a List, but with one critical difference: it is Immutable (Unchangeable).

Think of a List as a whiteboard (you can write, erase, and rewrite).

A tuple is an ordered collection of elements stored in a single variable. It is defined using parentheses ().

Key Characteristics:

  1. Immutable: You cannot add, remove, or change items after creation.
  2. Ordered: Items have a fixed position (0, 1, 2…n).
  3. Allow Duplicates: (1, 1, 1) is perfectly valid.
  4. Heterogeneous: Can mix data types: (“Apple”, 10, True).
  5. Faster: Tuples are faster and lighter on memory than lists.

2. Creating Tuples

There are specific nuances to creating tuples correctly.

1. Standard Syntax

# Standard creation
my_tuple = ("apple", "banana", "cherry")

# Mixed data types
mixed = (1, "Hello", 3.14, True)

# Without parentheses (Tuple Packing)
# Python assumes values separated by commas are a tuple
coordinates = 10, 20
print(type(coordinates)) # <class 'tuple'>

2. The Constructor

# Using the built-in function (Double brackets needed)
my_tuple = tuple(("apple", "banana", "cherry"))

3. The “Comma Trap”

This is the most common mistake beginners make. Python does not recognize a single value in parentheses as a tuple unless you add a comma.

# NOT a tuple (It interprets this as a String)
not_tuple = ("apple")
print(type(not_tuple)) # <class 'str'>

# IS a tuple (Notice the trailing comma)
is_tuple = ("apple",)
print(type(is_tuple))  # <class 'tuple'>

3. Accessing Elements

Accessing tuple items works exactly like Lists.

  • Indexing: tup[0] (First item)
  • Negative Indexing: tup[-1] (Last item)
  • Slicing: tup[start:stop] (Range of items)
data = (10, 20, 30, 40, 50)

print(data[1])     # 20
print(data[-1])    # 50
print(data[1:4])   # (20, 30, 40)

4. The Immutability Rule

Once a tuple is created, you cannot change it.

x = (10, 20, 30)

# This creates an Error: 'tuple' object does not support item assignment
# x[1] = 99 

The Workaround (How to Update)

If you absolutely must change a tuple, you have to “cheat” by converting it.

  1. Convert Tuple → List.
  2. Change the List.
  3. Convert List → Tuple.
x = ("apple", "banana", "cherry")

# Step 1: Convert to Mutable List
y = list(x)

# Step 2: Change item
y[1] = "kiwi"

# Step 3: Convert back to Immutable Tuple
x = tuple(y)

print(x) # ('apple', 'kiwi', 'cherry')

5. Operations on Tuples

Concatenation +

Join two tuples to create a new tuple.

tuple1 = ("a", "b")
tuple2 = (1, 2)

result = tuple1 + tuple2
print(result) # ('a', 'b', 1, 2)

Repetition *

Repeat the tuple elements.

fruits = ("apple",)
print(fruits * 3) # ('apple', 'apple', 'apple')

6. Unpacking Tuples

Usually, we assign a tuple to a variable. Unpacking is the reverse: extracting values back into variables.

Basic Unpacking

The number of variables must match the number of items exactly.

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)  # apple
print(yellow) # banana

Asterisk * Unpacking

If you have many items and only want to grab the first few, use * to gather the rest into a list.

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)  # apple
print(red)    # ['cherry', 'strawberry', 'raspberry'] (List of remainders)

7. Tuple Methods

Because tuples are immutable, they only have two built-in methods.

MethodDescriptionExample
.count(val)Returns number of times val appears.tup.count(5)
.index(val)Returns index of first occurrence of val.tup.index(5)

8. Memory Optimization

You often hear “Tuples are faster than Lists,”

  1. Fixed Allocation: Lists are dynamic; they allocate extra “empty” memory in case you add items later. Tuples allocate exactly what is needed.
  2. Resource Caching: Python reuses memory for small tuples more aggressively.
import sys

my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)

print(sys.getsizeof(my_list))  # Output: ~104 bytes (Larger)
print(sys.getsizeof(my_tuple)) # Output: ~80 bytes (Smaller)

9. The Immutability – Nested Mutability

A tuple itself cannot be changed, but objects inside it might be changeable.

If a tuple contains a List, you can modify that list!

# A tuple containing a mutable list
my_tuple = (10, 20, ["A", "B"])

# Error: Cannot replace the list itself
# my_tuple[2] = [1, 2] 

# Valid: You CAN modify the list contents
my_tuple[2][0] = "Z"

print(my_tuple) 
# Output: (10, 20, ['Z', 'B'])

Rule: Tuples protect the structure, not necessarily the content if the content is mutable.

10. Tuples as Dictionary Keys

Dictionaries require their keys to be Hashable (unchangeable).

  • Lists: Mutable → Not Hashable → Cannot be keys.
  • Tuples: Immutable → Hashable → Can be keys.
# Storing coordinates
locations = {
    (35.6, 139.6): "Tokyo",
    (40.7, -74.0): "New York"
}

11. Named Tuples

Standard tuples (1, “John”) are confusing because you have to remember that index 0 is ID and 1 is Name. namedtuple solves this.

from collections import namedtuple

# 1. Define the structure
User = namedtuple("User", ["id", "name"])

# 2. Create the tuple
u1 = User(101, "Admin")

# 3. Access by name (Readable!)
print(u1.name)  # Output: Admin
print(u1.id)    # Output: 101

Summary Table: List vs Tuple

FeatureList []Tuple ()
Mutable?Yes (Changeable)No (Immutable)
SpeedSlowerFaster
MemoryUses more memoryUses less memory
MethodsMany (append, pop, sort)Few (count, index)
Use CaseData that changes (Shopping Cart)Data that is constant (Coordinates, Settings)
Contents
Scroll to Top