Python Interactive Guide - Step 1 Basic Syntax and Data Types (8) - Tuples
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 1: Basic Syntax and Data Types”.
1.5. Grouping Data
1.5.2. Tuples
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.
Creating Tuples
- 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
().
Tuple Property: Immutability
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.
Basic Tuple Operations
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
Tuple Methods
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)
Converting Between Tuples and Lists
- Tuples can be converted to lists using the
listfunction. - Lists can be converted to tuples using the
tuplefunction.
Functions That Work with Tuples
The following functions can be applied to tuples, just like lists:
min(tuple),max(tuple): Get minimum or maximum valuesum(tuple): Calculate sum of numberssorted(tuple): Return elements sorted as a listall(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.)
When to Use Tuples vs Lists
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
For data structures that don’t need to change, it’s better to use tuples.
Type Conversion with bool
- Like lists, applying the
boolfunction to a tuple returnsFalsefor empty tuples (()) andTruefor any non-empty tuple.
Tuple Summary
Let’s practice what we’ve learned about tuples with some exercises.
Create a program that works with RGB (red, green, blue) color information stored in tuples.
- Create a tuple
redwith RGB values(255, 0, 0)(representing red color) - Create a tuple
greenwith RGB values(0, 255, 0)(representing green color) - Create a tuple
bluewith RGB values(0, 0, 255)(representing blue color) - Create a tuple
primary_colorscontaining all three color tuples - Display the second element (green color) of
primary_colors - Get and display the blue value (last element) of the
bluetuple - Display the length of
primary_colors
Sample Solution
Create a tuple of weekdays and perform various operations on it.
- Create a tuple
weekdayscontaining the days of the week in English (Monday through Sunday) - Create a tuple
weekendcontaining just Saturday and Sunday (extract from weekdays using indexes) - Convert
weekdaysto a list and store it in a variable calledweekdays_list - Add “Holiday” to
weekdays_list - Convert
weekdays_listback to a tuple and store it in a variable callednew_weekdays - Display the lengths of both the original
weekdaysand the newnew_weekdaystuples
Sample Solution
Extract information from a tuple containing university student data (student ID, name, year, major).
- Create a tuple
studentcontaining(12345, "John Smith", 3, "Computer Science") - Use unpacking to assign the student ID, name, year, and major to separate variables
- Use unpacking to separate student ID, name, and other information
- Use unpacking to extract only the student’s name and major, ignoring the ID and year
- Display all the extracted information