Reading history

Python Tuples: Create, Unpack and Tuple vs List

3 min read 0 views

Learn Python tuples: creating them, the one-item comma rule, unpacking, immutability, count() and index(), and when to use a tuple instead of a list.

A tuple is an ordered collection, like a list, that cannot be changed after it is created. That fixed nature makes tuples a good fit for data that belongs together and should stay that way: a pair of coordinates, a date, a database row. This lesson covers creating tuples, unpacking them, their two methods, and when to choose a tuple over a list.

In this lesson you will learn

  • How to create tuples, including the one-item tuple trap
  • Indexing, slicing and unpacking
  • Why tuples are immutable and why that is useful
  • The count() and index() methods
  • Tuples vs lists

Creating and Unpacking Tuples

point = (3, 4)
print(point[0], point[-1])

single = (5,)        # the comma makes it a tuple
not_tuple = (5)
print(type(single).__name__, type(not_tuple).__name__)

x, y = point          # unpacking
print("x =", x, "y =", y)

a, b = 1, 2
a, b = b, a           # swap using tuples
print(a, b)

try:
    point[0] = 10
except TypeError as e:
    print("Error:", e)

Output

3 4
tuple int
x = 3 y = 4
2 1
Error: 'tuple' object does not support item assignment
  • Indexing works as it does for lists: point[0] is the first item, point[-1] the last.
  • The comma makes the tuple, not the brackets. (5,) is a tuple; (5) is just the number 5 in brackets.
  • Unpacking assigns each item to its own variable: x, y = point.
  • a, b = b, a swaps two values, using a tuple behind the scenes.
  • Trying to change an item raises a TypeError.

Methods, Slicing and Tuples as Keys

colors = ("red", "green", "blue", "green")
print(colors.count("green"), colors.index("blue"))
print(colors[1:3])
print("red" in colors)

# tuples can be dictionary keys, lists cannot
distance = {("Dhaka", "Sylhet"): 245, ("Dhaka", "Khulna"): 270}
print(distance[("Dhaka", "Sylhet")])

first, *rest = (10, 20, 30, 40)
print(first, rest)

record = ("Nabil", 23)
name, age = record
print(f"{name} is {age}")

Output

2 2
('green', 'blue')
True
245
10 [20, 30, 40]
Nabil is 23
  • Tuples have just two methods: count() and index(). Anything that would change the tuple, like append or sort, does not exist.
  • Slicing returns a new tuple.
  • Because tuples cannot change, they can serve as dictionary keys, which a list never can.
  • first, *rest = ... puts the first item in first and collects the rest into a list.

Tuple or List?

TupleList
Syntax(1, 2, 3)[1, 2, 3]
Can change?NoYes
Usable as a dict key?Yes (if its items are immutable)No
Typical useA fixed record: coordinates, RGB colour, a rowA growing collection of similar items
MemorySlightly smallerSlightly larger

You can convert between them with tuple(my_list) and list(my_tuple). See Python Lists for the mutable version.

Common Mistakes

  1. Forgetting the comma in a one-item tuple.
  2. Unpacking into the wrong number of variables. a, b = (1, 2, 3) raises ValueError; use a, *b for the extra items.
  3. Assuming everything inside is frozen. A tuple holding a list cannot swap the list for another object, but the list itself can still change.

Practice Exercises

Exercise 1. Given dob = (2004, 8, 15), unpack it and print 15/8/2004.

Show answer
year, month, day = (2004, 8, 15)
print(f"{day}/{month}/{year}")

Exercise 2. “Add” 4 to the tuple (1, 2, 3).

Show answer

Tuples cannot change, so create a new one: t = (1, 2, 3) + (4,) gives (1, 2, 3, 4).

Frequently Asked Questions

Why use a tuple if a list can do everything?

A tuple tells readers the data will not change, protects it from accidental edits, and can be used as a dictionary key or set item.

Is a tuple faster than a list?

Tuples are slightly faster to create and use a little less memory, but the difference rarely matters. Choose based on whether the data should change.

Summary

  • Tuples are ordered and immutable; the comma creates them.
  • Unpacking assigns each item to its own variable in one line.
  • Only count() and index() are available.
  • Use tuples for fixed records and dictionary keys, and lists for collections that change.

Next: Python Sets.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *