Tuples

Python - A Quick Start for existing Programers

3 min read

Published Sep 16 2025, updated Aug 17 2026


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 valuet = (42,)​# the ( ) can be ommitted in many cases, eg this is still a tuplex = 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])        # 3print("Last:", nums[-1])        # 5print("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 = tprint(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 unpackingpoint = (3, 4)x, y = pointprint(x, y)  # 3 4​# Extended Unpacking (*)t = (1, 2, 3, 4, 5)a, *middle, e = tprint(a, middle, e)  # 1 [2, 3, 4] 5​# Nested Unpackingnested = (1, (2, 3), 4)a, (b, c), d = nestedprint(a, b, c, d)  # 1 2 3 4​# Using with Loopspairs = [(1, 2), (3, 4), (5, 6)]for x, y in pairs:    print(x + y)# Output: 3, 7, 11​# Function Return Valuesdef 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))       # 5print("Min:", min(nums))         # 1print("Max:", max(nums))         # 5print("Sum:", sum(nums))          # 14print("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))   # Trueprint("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))   # 2print("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 tuplesprint((1, 2, 3) == (1, 2, 3))  # Trueprint((1, 2, 3) != (1, 2, 4))  # True​# Less / greater based on first differing elementprint((1, 2, 3) < (1, 2, 4))   # True, because 3 < 4print((1, 3) > (1, 2, 99))     # True, because 3 > 2​# Shorter tuple is smaller if all compared elements are equalprint((1, 2) < (1, 2, 0))      # Trueprint((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])       # 3print("Last element:", nums[-1])       # 5print("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))   # 2print("Index of 4 in nums:", nums.index(4))   # 2​# --- Built-in Functions ---print("Length of nums:", len(nums))       # 5print("Min of nums:", min(nums))          # 1print("Max of nums:", max(nums))          # 5print("Sum of nums:", sum(nums))          # 14print("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))   # Trueprint("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 guaranteedprint("tuple({'a':1,'b':2}):", tuple({"a":1,"b":2}))  # keys onlyprint("tuple(range(5)):", tuple(range(5)))    # (0,1,2,3,4)​# --- Unpacking ---a, b, c, d, e = numsprint("Unpacked nums:", a, b, c, d, e)  # 3 1 4 1 5​# Extended unpackingt = (1, 2, 3, 4, 5)x, *middle, y = tprint("Extended unpacking:", x, middle, y)  # 1 [2,3,4] 5​# Nested unpackinga, (b, c), d = nestedprint("Nested unpacking:", a, b, c, d)      # 1 2 3 4​# --- Comparisons ---print("(1,2,3) == (1,2,3):", (1,2,3) == (1,2,3))   # Trueprint("(1,2,3) < (1,2,4):", (1,2,3) < (1,2,4))     # Trueprint("(1,3) > (1,2,99):", (1,3) > (1,2,99))       # Trueprint("(1,2) < (1,2,0):", (1,2) < (1,2,0))         # Trueprint("(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)
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact