Back to Python Notes
Topic #203

Tuple in Python

By the end of this lesson, you will understand how to create and use tuples in Python, recognize their immutability, and know when they are preferable to lists.

What it is

A tuple is an ordered, immutable collection of elements. Unlike lists, which can be modified after creation, a tuple’s contents cannot be changed once defined. This makes tuples ideal for grouping related data that should remain constant throughout the program's execution. Think of a tuple as a fixed record or a coordinate pair (x, y) where the values define a specific state that shouldn't drift.

Key characteristics include:

  • Ordered: Elements maintain their insertion order and can be accessed by index.
  • Immutable: You cannot add, remove, or change items after creation.
  • Heterogeneous: Tuples can contain different data types (e.g., integers, strings, other tuples).

Why it matters

  • Data Integrity: Prevents accidental modification of critical configuration data or constants.
  • Performance: Tuples are slightly faster to iterate over and consume less memory than equivalent lists because their size is fixed at creation.
  • Dictionary Keys: Because they are hashable (immutable), tuples can be used as keys in dictionaries, whereas lists cannot.
  • Multiple Return Values: Functions often return multiple values as a tuple, allowing clean unpacking into variables.

Syntax or steps

Tuples are defined using parentheses (), though the parentheses are optional if commas are present. The comma is the actual tuple constructor.

  1. Create a tuple: t = (1, 2, 3)
  2. Create a single-element tuple: t = (1,) (note the trailing comma)
  3. Access elements: t[0]
  4. Unpack elements: a, b, c = t

Example

# Creating tuples
coordinates = (10, 20)
person_info = ("Alice", 30, "Engineer")

# Accessing elements
print(f"X coordinate: {coordinates[0]}")
print(f"Name: {person_info[0]}")

# Unpacking (common with function returns)
def get_dimensions():
    return (800, 600)

width, height = get_dimensions()
print(f"Resolution: {width}x{height}")

# Attempting to modify raises an error
try:
    coordinates[0] = 5
except TypeError as e:
    print(f"Error caught: {e}")

In this example, coordinates stores x and y values. We access them via indexing. The function get_dimensions returns a tuple, which we immediately unpack into width and height. Finally, attempting to assign a new value to coordinates[0] triggers a TypeError, demonstrating immutability.

Common mistakes

  • Missing the trailing comma: Writing t = (1) creates an integer, not a tuple. Always use t = (1,) for single-element tuples.
  • Confusing mutability: Remember that while the tuple itself is immutable, if it contains a mutable object (like a list), that inner object can still be modified. t = ([1, 2],) allows t[0].append(3).
  • Using tuples for dynamic collections: If you need to add or remove items frequently, use a list instead. Forcing updates on a tuple requires creating a new tuple entirely, which is inefficient.

When to use it

Choose between a tuple and a list based on whether the data structure needs to change.

FeatureTupleList
MutabilityImmutableMutable
Use CaseFixed records, coordinates, configCollections that grow/shrink
Hashable?Yes (if elements are hashable)No
MemorySlightly smallerSlightly larger

Practice

Guided Exercise: Create a tuple named rgb_color containing three integers representing Red, Green, and Blue values (e.g., 255, 100, 50). Print the green value.

Challenge: Write a function swap(a, b) that takes two numbers and returns them swapped as a tuple. Use tuple unpacking to call it: x, y = swap(1, 2).

Hint: The return statement should look like return (b, a).

Quick check

Question: Why can a tuple be used as a dictionary key but a list cannot?

Answer: Dictionary keys must be hashable. Hashability requires immutability so that the key's identity doesn't change after insertion. Lists are mutable, so their hash value could theoretically change, breaking the dictionary's internal structure. Tuples are immutable, making them safe to hash.

Summary

Tuples provide a lightweight, immutable way to group related data. Use them when the collection size and content are fixed, such as for coordinates, database records, or function return values. Their immutability ensures data integrity and enables usage as dictionary keys.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Tuple in Python – FAQs

Quick answers about learning Tuple in Python in Python.

This free note from Coding Now Tech Institute explains Tuple in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Tuple in Python, is 100% free with no signup required.
With focused practice, most students grasp Tuple in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now