KAHIBARO Bookshelves
Discord Login Register

8.2. Tuples

What is a Tuple?

A tuple is an ordered collection of items, similar to a list, but cannot be changed after it is created.

  • Ordered: items keep their position (index 0, 1, 2, …).
  • Can store mixed types: numbers, strings, booleans, etc.
  • Immutable: you cannot add, remove, or change items once the tuple is created.

Tuples are written using parentheses () instead of square brackets [].

numbers = (10, 20, 30)
person = ("Alice", 30, True)

Creating Tuples

Basic tuples

You create a tuple by putting values inside parentheses, separated by commas:

empty_tuple = ()
colors = ("red", "green", "blue")
mixed = ("Alice", 25, 1.75, True)

Tuple without parentheses

Python lets you omit the parentheses in many cases. The commas are what really make a tuple:

coords = 10, 20
print(coords)        # (10, 20)
print(type(coords))  # <class 'tuple'>

Still, using parentheses is clearer and recommended for beginners.

One‑item (single-element) tuples

A common beginner trap: a single value in parentheses is not a tuple:

not_a_tuple = (5)
print(type(not_a_tuple))   # <class 'int'>

To make a one‑item tuple, you must add a trailing comma:

one_item = (5,)
print(type(one_item))  # <class 'tuple'>
another_one = "hello",
print(type(another_one))  # <class 'tuple'>

Accessing Tuple Items

Tuples use zero-based indexing, just like strings and lists.

point = (3, 4, 5)
print(point[0])  # 3
print(point[1])  # 4
print(point[2])  # 5

You can also use negative indexes:

  • -1 = last item
  • -2 = second-to-last, and so on.
colors = ("red", "green", "blue")
print(colors[-1])  # "blue"
print(colors[-2])  # "green"

Slicing tuples

You can get a slice (part) of a tuple using start:stop:

data = (10, 20, 30, 40, 50)
print(data[1:4])   # (20, 30, 40)
print(data[:3])    # (10, 20, 30)
print(data[2:])    # (30, 40, 50)

Slicing a tuple returns a new tuple.

Tuple Immutability

Tuples are immutable: after you create one, you cannot change its contents.

This means you cannot:

  • Reassign an individual item.
  • Append new items.
  • Remove items.
nums = (1, 2, 3)
# All of these cause errors:
# nums[0] = 10       # TypeError
# nums.append(4)     # AttributeError
# del nums[1]        # TypeError

If you want to "change" a tuple, you actually create a new tuple.

nums = (1, 2, 3)
new_nums = (0,) + nums + (4,)
print(new_nums)  # (0, 1, 2, 3, 4)

Or convert to a list, change it, then convert back:

nums = (1, 2, 3)
temp_list = list(nums)  # convert to list
temp_list.append(4)
nums = tuple(temp_list)  # convert back to tuple
print(nums)  # (1, 2, 3, 4)

When to Use Tuples Instead of Lists

Use a tuple when:

  • Your data should not change.
  • The collection represents a single, fixed object, like coordinates, a date, or a record.

Examples:

# Coordinates (x, y)
position = (100, 200)
# RGB color (red, green, blue)
color = (255, 128, 0)
# Birth date (year, month, day)
birth_date = (1990, 5, 23)

Tuples are often used for fixed structures where each position has a meaning.

Tuple Operations

Tuples support many of the same operations as strings and lists (except mutation).

Length

Use len() to count the items:

values = (10, 20, 30, 40)
print(len(values))  # 4

Membership: `in` and `not in`

Check if a value is in a tuple:

nums = (1, 2, 3, 4)
print(3 in nums)      # True
print(5 in nums)      # False
print(5 not in nums)  # True

Concatenation and repetition

You can join tuples with + and repeat them with *:

a = (1, 2)
b = (3, 4)
c = a + b
print(c)  # (1, 2, 3, 4)
d = a * 3
print(d)  # (1, 2, 1, 2, 1, 2)

These operations create new tuples, because the original ones cannot be changed.

Tuple Methods

Tuples have a very small set of methods (because they are immutable).

The two common ones:

  • count(value) – how many times a value appears.
  • index(value) – position of the first occurrence.
nums = (1, 2, 2, 3, 2)
print(nums.count(2))   # 3
print(nums.index(3))   # 3

If index() doesn’t find the value, it raises a ValueError.

nums = (1, 2, 3)
# nums.index(5)  # ValueError: tuple.index(x): x not in tuple

Tuple Packing and Unpacking

Packing

Packing means putting multiple values into a tuple in a single assignment:

person = "Alice", 25, "Paris"   # packed into a tuple
print(person)                   # ('Alice', 25, 'Paris')

Unpacking

Unpacking means assigning elements of a tuple to multiple variables at once.

person = ("Alice", 25, "Paris")
name, age, city = person
print(name)  # Alice
print(age)   # 25
print(city)  # Paris

The number of variables must match the number of tuple items:

data = (1, 2, 3)
# a, b = data       # ValueError: not enough values to unpack
# a, b, c, d = data # ValueError: too many values to unpack

Using `_` to ignore values

You can use _ as a throwaway variable for values you don't care about:

record = ("Bob", 30, "Engineer")
name, _, job = record
print(name)  # Bob
print(job)   # Engineer

This doesn’t change how Python works; _ is just a normal variable name by convention.

Unpacking with `*` (star)

You can use * to collect "the rest" of the values into a list:

numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)   # 10
print(middle)  # [20, 30, 40]
print(last)    # 50

Tuples as Dictionary Keys (Preview)

Because tuples are immutable, they can be used as keys in dictionaries (unlike lists).

Example (you will see dictionaries in another chapter, but this is useful to know):

# a tuple representing a point (x, y)
point = (10, 20)
locations = {
    point: "Tree",
}
print(locations[(10, 20)])  # "Tree"

Lists cannot be used as keys, but tuples can, which is one practical reason tuples exist.

Nested Tuples

Tuples can contain other tuples (and other collections):

grid = (
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9),
)
print(grid[0])     # (1, 2, 3)
print(grid[1][2])  # 6

This is useful to represent 2D data (like a grid or matrix) that should not change.

Common Tuple Mistakes for Beginners

1. Forgetting the comma in single-element tuples

value = (5)    # just 5, not a tuple
print(type(value))  # <class 'int'>
value = (5,)   # now it's a tuple
print(type(value))  # <class 'tuple'>

2. Trying to modify a tuple item

data = (1, 2, 3)
# data[0] = 10  # TypeError

If you need to change it, convert to a list, or use a list instead of a tuple from the start.

3. Mismatch when unpacking

coords = (10, 20, 30)
# x, y = coords      # ValueError: not enough values to unpack
# x, y, z, w = coords  # ValueError: too many values to unpack

Always ensure the number of variables matches the number of tuple items (unless you use * to collect extras).

Practice Ideas

Try writing small snippets that:

  1. Create a tuple describing yourself: (name, age, country), then unpack it into variables.
  2. Create a tuple of 5 numbers and:
    • Print the first and last.
    • Print the length.
    • Check whether a certain number is in the tuple.
  3. Make a "coordinate" tuple (x, y), then use it as a key in a small dictionary (after reading the dictionaries chapter).
  4. Experiment with converting between lists and tuples using list() and tuple().

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms