7.1. Creating Tuples#

import sys
from pathlib import Path

# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

# Add project root to path
sys.path.insert(0, str(project_root))

# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download

Tuples in Python can be created in several ways, primarily:

  • Using tuple literals: through the use of commas and optional parentheses

  • by using the built-in tuple() constructor

How to create

Method

Example

Result

Use parentheses with comma-separated values

Parentheses

(1, 2, 3)

(1, 2, 3)

Write comma-separated values without parentheses

Tuple packing

1, 2, 3

(1, 2, 3)

Use empty parentheses

Empty tuple

()

()

Add a trailing comma for one value

Single-item tuple

(1,) or 1,

(1,)

Use the tuple constructor on an iterable

Constructor

tuple([1, 2, 3])

(1, 2, 3)

7.1.1. Tuple Literals#

To create a tuple, you can write a comma-separated list of values.

status = 'NEW', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CLOSED'
type(status)
tuple

Parentheses are optional, but it is common to use them with tuples.

t1 = ('NEW', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CLOSED')
print(t1)
print(type(t1))

t2 = 'NEW', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CLOSED'  # tuple packing
print(t2)
print(type(t2))
('NEW', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CLOSED')
<class 'tuple'>
('NEW', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CLOSED')
<class 'tuple'>

7.1.2. Single-Element Tuples#

To make a one-element tuple, include a trailing comma. Parentheses are optional.

t1 = ('URGENT',)
print(type(t1))
print(t1[0])

t2 = 'URGENT',               # tuple packing with one element
print(type(t2))
print(t2[0])
<class 'tuple'>
URGENT
<class 'tuple'>
URGENT

However, a single value inside parentheses is not a tuple without a comma.

t2 = ('URGENT')
type(t2)
str

7.1.3. tuple() Constructor#

Another way to create a tuple is with the built-in function/type constructor tuple. With no argument, it creates an empty tuple.

If the argument is a sequence (list, tuple, or string), the tuple constructor returns a tuple containing the elements of that sequence — and list works the same way in reverse.

t = tuple(['Laptop', 'Mouse', 'Keyboard', 'Monitor'])
print(t)
print(type(t))

l = list(('Laptop', 'Mouse', 'Keyboard', 'Monitor'))
print(l)
print(type(l))
('Laptop', 'Mouse', 'Keyboard', 'Monitor')
<class 'tuple'>
['Laptop', 'Mouse', 'Keyboard', 'Monitor']
<class 'list'>

7.1.4. Empty Tuple#

t = tuple()

print(t)
print(type(t))
()
<class 'tuple'>

7.1.5. Nested Tuples#

A nested tuple is a tuple that contains one or more tuples as elements. This is useful for representing multi-dimensional or grouped data, such as a matrix or a list of coordinate pairs. You access elements using chained indexing: the first index selects the inner tuple, and the second index selects an element within it.

# A tuple containing other tuples
matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

# Access the second row
print(matrix[1])        # (4, 5, 6)

# Access the third element of the second row
print(matrix[1][2])     # 6

# Tuple of coordinate pairs
points = ((0, 0), (1, 2), (3, 4))
for x, y in points:
    print(f'x={x}, y={y}')
(4, 5, 6)
6
x=0, y=0
x=1, y=2
x=3, y=4
### Exercise: Creating Tuples
#   1. Create a tuple named `colors` containing "red", "green", "blue" using parentheses.
#   2. Create a single-element tuple named `one` containing the integer 42.
#   3. Create a tuple named `letters` by passing the string "hello" to the tuple() constructor.
#   4. Print each tuple and its type.
### Your code starts here.




### Your code ends here.

Hide code cell source

### solution

colors = ("red", "green", "blue")
one = (42,)
letters = tuple("hello")

print(colors, type(colors))
print(one, type(one))
print(letters, type(letters))
('red', 'green', 'blue') <class 'tuple'>
(42,) <class 'tuple'>
('h', 'e', 'l', 'l', 'o') <class 'tuple'>

7.1.6. Accessing Elements#

7.1.7. Indexing and Slicing#

Tuples support indexing and slicing the same way lists do.

t = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri')
print(t)
t[0]
('Mon', 'Tue', 'Wed', 'Thu', 'Fri')
'Mon'

The slice operator selects a range of elements.

t[1:3]
('Tue', 'Wed')
### Exercise: Indexing and Slicing
#   Given the tuple: t = ('a', 'b', 'c', 'd', 'e')
#   1. Print the first and last elements using indexing.
#   2. Print the middle three elements using slicing.
#   3. Print the tuple in reverse using a slice.
### Your code starts here.

t = ('a', 'b', 'c', 'd', 'e')



### Your code ends here.

Hide code cell source

### solution

t = ('a', 'b', 'c', 'd', 'e')

print(t[0], t[-1])    # first and last
print(t[1:4])          # middle three
print(t[::-1])         # reversed
a e
('b', 'c', 'd')
('e', 'd', 'c', 'b', 'a')