Skip to content

Python 3 - Tuples

A tuple is an ordered sequence of Python objects. Similar to lists, tuples store a collection of items. However, the defining characteristic of tuples is their immutability – once a tuple is created, its elements cannot be changed, added, or removed.

Syntax: Tuples are typically created by listing comma-separated values, optionally enclosed in parentheses ().

# Creating tuples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d" # Parentheses are optional
# Empty tuple
empty_tup = ()
# Tuple with a single element (requires a trailing comma)
single_tup = (50,)
not_a_tuple = (50) # This is just the integer 50 due to parentheses rules
print(type(single_tup)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'int'>

Like lists and strings, tuples are indexed starting from 0. They support slicing, concatenation, and other sequence operations.

Use square brackets [] with the index or slice notation to access elements within a tuple.

#!/usr/bin/env python3
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print(f"tup1[0]: {tup1[0]}")
print(f"tup2[1:5]: {tup2[1:5]}") # Elements from index 1 up to (but not including) 5
print(f"tup1[-1]: {tup1[-1]}") # Last element

Output:

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
tup1[-1]: 2000

Tuples are immutable. You cannot change an element within a tuple after it’s created.

#!/usr/bin/env python3
tup1 = (12, 34.56)
# This action is INVALID and will raise a TypeError:
# tup1[0] = 100 # TypeError: 'tuple' object does not support item assignment

However, you can create new tuples by concatenating or slicing existing ones.

#!/usr/bin/env python3
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Create a new tuple by combining tup1 and tup2
tup3 = tup1 + tup2
print(f"New combined tuple: {tup3}")

Output:

New combined tuple: (12, 34.56, 'abc', 'xyz')

Deleting Tuple Elements (or the Whole Tuple)

Section titled “Deleting Tuple Elements (or the Whole Tuple)”

Because tuples are immutable, you cannot remove individual elements from a tuple.

You can, however, delete an entire tuple variable using the del statement. This removes the name’s binding to the tuple object (which might then be garbage collected if no other references exist).

#!/usr/bin/env python3
tup_to_delete = ('physics', 'chemistry', 1997, 2000)
print(f"Before deletion: {tup_to_delete}")
del tup_to_delete
# Trying to access tup_to_delete after deletion will raise a NameError:
# print("After deleting tup:")
# print(tup_to_delete) # NameError: name 'tup_to_delete' is not defined

To effectively ‘remove’ an element, you must create a new tuple by slicing and concatenating the parts you want to keep.

#!/usr/bin/env python3
original_tup = (1, 2, 3, 4, 5)
# Create a new tuple without the element at index 2 (value 3)
new_tup = original_tup[:2] + original_tup[3:]
print(f"New tuple without element at index 2: {new_tup}") # Output: (1, 2, 4, 5)

Tuples support common sequence operations:

Python ExpressionResultDescription
len((1, 2, 3))3Length (number of items)
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation (creates a new tuple)
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')Repetition (creates a new tuple)
3 in (1, 2, 3)TrueMembership testing
for x in (1, 2, 3): print(x, end=' ')1 2 3Iteration
max((1, 5, 2))5Maximum value
min((1, 5, 2))1Minimum value

Indexing (accessing single elements) and slicing (extracting subsequences) work just like with lists and strings.

languages = ('C++', 'Java', 'Python', 'Go')
Python ExpressionResultDescription
languages[2]'Python'Access element at index 2 (0-based)
languages[-1]'Go'Negative indexing: count from the right (-1 is the last element)
languages[1:]('Java', 'Python', 'Go')Slicing: elements from index 1 to the end
languages[:2]('C++', 'Java')Slicing: elements from the beginning up to (not including) index 2
languages[0:3:2]('C++', 'Python')Slicing with step: from index 0 to 3, taking every 2nd element

Use tuples when:

  • You want to ensure the data cannot be changed after creation (data integrity).
  • You need a sequence that can be used as a dictionary key or stored in a set (requires immutable elements).
  • You want to represent a fixed collection of items, like coordinates (x, y) or RGB color values.
  • You might gain a slight performance advantage for iteration compared to lists (though often negligible).

Use lists when:

  • You need a collection of items that might need to grow, shrink, or have its elements modified.
  • The order of items is important, and you need methods like append(), insert(), remove(), sort(), etc.

Python includes a function specifically related to tuples:

FunctionDescription
tuple(iterable)Converts an iterable (like a list, string, or range) into a tuple. If the argument is already a tuple, it’s returned unchanged.
#!/usr/bin/env python3
my_list = [1, 2, 3]
my_string = "abc"
tuple_from_list = tuple(my_list)
print(f"Tuple from list: {tuple_from_list}")
tuple_from_string = tuple(my_string)
print(f"Tuple from string: {tuple_from_string}")

Output:

Tuple from list: (1, 2, 3)
Tuple from string: ('a', 'b', 'c')