Contents

Python Quick Guide - Step 1 Basic Syntax and Data Types (8) - Tuples

Info
  • This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
  • The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
  • You can run and see the results of each code example.
    Feel free to experiment with the code - reloading the page will reset the content.

This is a continuation of “Step 1: Basic Syntax and Data Types”.

Besides lists, tuples (tuple) are another data type for organizing multiple items.
The key characteristic of tuples is that they are immutable, meaning once created, their elements cannot be modified.

  • Tuples are created by placing elements separated by commas (,) inside parentheses ((, )).
  • When creating a tuple with just one element, you must include a trailing comma (,).
  • Parentheses can be omitted.
  • An empty tuple is created with ().

The most important characteristic of tuples is that they are immutable.
Once created, you cannot change, add, or remove tuple elements.

  • While tuples themselves are immutable, the contents of mutable objects (like lists) stored within a tuple can still be modified.
    • Among the data types we’ve covered so far, only lists are mutable.

Tuples support the following operations, similar to lists:

  • Element access by index tuple[0]
  • Finding length len(tuple)
  • Membership testing x in tuple
  • Slicing tuple[1:3]
  • Unpacking x, y = tuple

Since tuples are immutable, they have fewer methods than lists and none that would modify elements.

  • Get position tuple.index(x)
  • Count occurrences tuple.count(x)
  • Tuples can be converted to lists using the list function.
  • Lists can be converted to tuples using the tuple function.

The following functions can be applied to tuples, just like lists:

  • min(tuple), max(tuple): Get minimum or maximum value
  • sum(tuple): Calculate sum of numbers
  • sorted(tuple): Return elements sorted as a list
  • all(tuple), any(tuple): Check boolean values in the tuple

Note that the sorted function returns a list, not a tuple.
(If you want a tuple, you can convert it using the tuple function.)

Both tuples and lists store collections of items, but they have different characteristics and use cases:

  • Tuples are appropriate when:

    • You have data that should not change after creation (e.g., coordinates, days of the week)
    • You want to ensure data immutability
    • You need to use the collection as a dictionary key (we’ll learn this later)
  • Lists are appropriate when:

    • You need to add, remove, or modify elements
    • Your data changes dynamically
Tuple and List Performance
Since tuples are immutable, they can use less memory and be processed faster than lists in some cases.
For data structures that don’t need to change, it’s better to use tuples.
  • Like lists, applying the bool function to a tuple returns False for empty tuples (()) and True for any non-empty tuple.

Let’s practice what we’ve learned about tuples with some exercises.

📚Exercise 1: Basic Tuple Operations

Create a program that works with RGB (red, green, blue) color information stored in tuples.

  1. Create a tuple red with RGB values (255, 0, 0) (representing red color)
  2. Create a tuple green with RGB values (0, 255, 0) (representing green color)
  3. Create a tuple blue with RGB values (0, 0, 255) (representing blue color)
  4. Create a tuple primary_colors containing all three color tuples
  5. Display the second element (green color) of primary_colors
  6. Get and display the blue value (last element) of the blue tuple
  7. Display the length of primary_colors
Sample Solution
📚Exercise 2: Converting Between Tuples and Lists

Create a tuple of weekdays and perform various operations on it.

  1. Create a tuple weekdays containing the days of the week in English (Monday through Sunday)
  2. Create a tuple weekend containing just Saturday and Sunday (extract from weekdays using indexes)
  3. Convert weekdays to a list and store it in a variable called weekdays_list
  4. Add “Holiday” to weekdays_list
  5. Convert weekdays_list back to a tuple and store it in a variable called new_weekdays
  6. Display the lengths of both the original weekdays and the new new_weekdays tuples
Sample Solution
📚Exercise 3: Tuple Unpacking

Extract information from a tuple containing university student data (student ID, name, year, major).

  1. Create a tuple student containing (12345, "John Smith", 3, "Computer Science")
  2. Use unpacking to assign the student ID, name, year, and major to separate variables
  3. Use unpacking to separate student ID, name, and other information
  4. Use unpacking to extract only the student’s name and major, ignoring the ID and year
  5. Display all the extracted information
Sample Solution

Related Content