Tuples

Python - A Quick Start for existing Programers

3 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

A tuple in Python is:

  • Ordered: elements have a fixed order and can be indexed.
  • Immutable: once created, elements cannot be added, removed, or changed.
  • Iterable: can be looped over, unpacked, sliced.
  • Heterogeneous: can hold different data types.
  • Performance: Tuples are slightly faster than lists for iteration and access, since they’re fixed-size and don’t need dynamic resizing so they are a better choice than lists for large data that won't change.
  • Less memory: Tuples use less memory than lists so are useful when using large fixed-size data.
  • (): Tuples are defined using ( ) standard brackets.

Examples:

point = (3, 4)
mixed = (1, "hello", 3.14)

# note, single element tuples need a trailing comma to denote that it is a tuple rather than a single value
t = (42,)

# the ( ) can be ommitted in many cases, eg this is still a tuple
x = 1, 2, 3

Python tuples are indexed collections, however you can also use negative indexing:

  • Zero-based indexing → the first element is at index 0, the second at 1, and so on.
  • Negative indexing → counts from the end: -1 is the last element, -2 the second-to-last, etc.

Examples:

nums = (3, 1, 4, 1, 5)

print("First:", nums[0])
# 3
print("Last:", nums[-1])
# 5
print("Slice [1:4]:", nums[1:4])
# (1, 4, 1)




Tuple unpacking

Tuple unpacking allows you to assign each element of a tuple to a separate variable in a single statement.

t = (1, 2, 3)
a, b, c = t
print(a, b, c)
# 1 2 3

Rules:

  1. Number of variables must match the number of elements in the tuple (unless using * for extended unpacking).
  2. Parentheses are optional in many cases: a, b, c = 1, 2, 3 works too.
  3. Supports nested unpacking for tuples inside tuples.
  4. Can be used in for loops, function returns, and multiple assignments.


Examples:

# Basic unpacking
point = (3, 4)
x, y = point
print(x, y)
# 3 4

# Extended Unpacking (*)
t = (1, 2, 3, 4, 5)
a, *middle, e = t
print(a, middle, e)
# 1 [2, 3, 4] 5

# Nested Unpacking
nested = (1, (2, 3), 4)
a, (b, c), d = nested
print(a, b, c, d)
# 1 2 3 4

# Using with Loops
pairs = [(1, 2), (3, 4), (5, 6)]
for x, y in pairs:
    print(x + y)
# Output: 3, 7, 11

# Function Return Values
def minmax(values):
    return min(values), max(values)

low, high = minmax([5, 1, 9, 3])
print(low, high)
# 1 9




Built-in functions used with tuples

Since tuples are iterable, all the common built-ins for iterables work:

  • len(tuple) → number of elements
  • min(tuple), max(tuple) → smallest/largest element
  • sum(tuple) → sum of elements (if numeric)
  • sorted(tuple) → returns a new list sorted from the tuple
  • enumerate(tuple) → index-value pairs
  • any(tuple), all(tuple) → logical checks
  • tuple(iterable) → casting from iterable to tuple

Examples:

nums = (3, 1, 4, 1, 5)

print("Length:", len(nums))
# 5
print("Min:", min(nums))
# 1
print("Max:", max(nums))
# 5
print("Sum:", sum(nums))
# 14
print("Sorted copy:", sorted(nums))
# [1, 1, 3, 4, 5]

print("Enumerate:")
for i, val in enumerate(nums):
    print(f" index={i}, value={val}")

print("Any > 4?", any(n > 4 for n in nums))
# True
print("All > 0?", all(n > 0 for n in nums))
# True




Tuples own functions

Tuples are immutable, so they only have two methods:

Function

Description

tuple.count(x)

Return number of occurrences of x.

tuple.index(x, [start], [end])

Return the first index of x (optional slice bounds).


Examples:

nums = (3, 1, 4, 1, 5)

print("Count of 1:", nums.count(1))
# 2
print("Index of 4:", nums.index(4))
# 2




Casting to a tuple in

You can call tuple(x) to create a tuple from any iterable (something you can loop over).

Works with:

  • Strings → breaks into a tuple of characters
  • Lists → converts into tuple of elements
  • Sets → unordered elements become a tuple
  • Dictionaries → by default, only keys are taken
  • Range objects → numbers expanded into a tuple
  • Other iterables (generators, iterators, files, custom classes that implement __iter__)

Does not work with non-iterables (like int, float, None) → raises TypeError.


Examples:

tuple("abc")
# ('a', 'b', 'c')

tuple([1,2,3])
# (1,2,3)

tuple({1,2,3})
# (1,2,3) order may vary

tuple({'a':1,'b':2})
# ('a', 'b')

tuple(range(5))
# (0,1,2,3,4)




Tuple Comparisons

Python compares tuples lexicographically (element by element, like words in a dictionary).

Rules:

  1. Compare the first elements of each tuple.
  2. If the first elements are equal, compare the next elements, and so on.
  3. The first pair of elements that differ decides the comparison.
  4. If all compared elements are equal but one tuple is shorter, the shorter tuple is considered smaller.
  5. Elements must be comparable types (e.g., numbers with numbers, strings with strings). Otherwise, a TypeError occurs.

Supported operators:

  • ==, != → equality / inequality
  • <, <=, >, >= → lexicographical ordering

Examples:

# Equal tuples
print((1, 2, 3) == (1, 2, 3))
# True
print((1, 2, 3) != (1, 2, 4))
# True

# Less / greater based on first differing element
print((1, 2, 3) < (1, 2, 4))
# True, because 3 < 4
print((1, 3) > (1, 2, 99))
# True, because 3 > 2

# Shorter tuple is smaller if all compared elements are equal
print((1, 2) < (1, 2, 0))
# True
print((1, 2, 3) > (1, 2))
# True

# Mixed types (not allowed)
try:
    print((1,) < ("a",))
except TypeError as e:
    print("Error:", e)




Full demonstration of tuples

# --- Creating tuples ---
empty = ()
single = (42,)
nums = (3, 1, 4, 1, 5)
mixed = (1, "hello", 3.14)
nested = (1, (2, 3), 4)

print("Empty tuple:", empty)
print("Single element tuple:", single)
print("Nums tuple:", nums)
print("Mixed tuple:", mixed)
print("Nested tuple:", nested)

# --- Indexing & Slicing ---
print("First element:", nums[0])
# 3
print("Last element:", nums[-1])
# 5
print("Slice [1:4]:", nums[1:4])
# (1, 4, 1)
print("Slice last two:", nums[-2:])
# (1, 5)

# --- Tuple Methods ---
print("Count of 1 in nums:", nums.count(1))
# 2
print("Index of 4 in nums:", nums.index(4))
# 2

# --- Built-in Functions ---
print("Length of nums:", len(nums))
# 5
print("Min of nums:", min(nums))
# 1
print("Max of nums:", max(nums))
# 5
print("Sum of nums:", sum(nums))
# 14
print("Sorted copy:", sorted(nums))
# [1, 1, 3, 4, 5]

print("Enumerate nums:")
for i, val in enumerate(nums):
    print(f" index={i}, value={val}")

print("Any > 4?", any(n > 4 for n in nums))
# True
print("All > 0?", all(n > 0 for n in nums))
# True

# --- Casting to tuple ---
print("tuple('abc'):", tuple("abc"))
# ('a', 'b', 'c')
print("tuple([1,2,3]):", tuple([1,2,3]))
# (1,2,3)
print("tuple({1,2,3}):", tuple({1,2,3}))
# order not guaranteed
print("tuple({'a':1,'b':2}):", tuple({"a":1,"b":2}))
# keys only
print("tuple(range(5)):", tuple(range(5)))
# (0,1,2,3,4)

# --- Unpacking ---
a, b, c, d, e = nums
print("Unpacked nums:", a, b, c, d, e)
# 3 1 4 1 5

# Extended unpacking
t = (1, 2, 3, 4, 5)
x, *middle, y = t
print("Extended unpacking:", x, middle, y)
# 1 [2,3,4] 5

# Nested unpacking
a, (b, c), d = nested
print("Nested unpacking:", a, b, c, d)
# 1 2 3 4

# --- Comparisons ---
print("(1,2,3) == (1,2,3):", (1,2,3) == (1,2,3))
# True
print("(1,2,3) < (1,2,4):", (1,2,3) < (1,2,4))
# True
print("(1,3) > (1,2,99):", (1,3) > (1,2,99))
# True
print("(1,2) < (1,2,0):", (1,2) < (1,2,0))
# True
print("(1,2,3) > (1,2):", (1,2,3) > (1,2))
# True

try:
     # invalid comparison
    print((1,) < ("a",))
except TypeError as e:
    print("Error on mixed types:", e)

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact