Python Quick Guide - Step 1 Basic Syntax and Data Types (8) - Tuples
- 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”.
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
list
function. - Lists can be converted to tuples using the
tuple
function.
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
bool
function to a tuple returnsFalse
for empty tuples (()
) andTrue
for 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
red
with RGB values(255, 0, 0)
(representing red color) - Create a tuple
green
with RGB values(0, 255, 0)
(representing green color) - Create a tuple
blue
with RGB values(0, 0, 255)
(representing blue color) - Create a tuple
primary_colors
containing all three color tuples - Display the second element (green color) of
primary_colors
- Get and display the blue value (last element) of the
blue
tuple - Display the length of
primary_colors
Sample Solution
Create a tuple of weekdays and perform various operations on it.
- Create a tuple
weekdays
containing the days of the week in English (Monday through Sunday) - Create a tuple
weekend
containing just Saturday and Sunday (extract from weekdays using indexes) - Convert
weekdays
to a list and store it in a variable calledweekdays_list
- Add “Holiday” to
weekdays_list
- Convert
weekdays_list
back to a tuple and store it in a variable callednew_weekdays
- Display the lengths of both the original
weekdays
and the newnew_weekdays
tuples
Sample Solution
Extract information from a tuple containing university student data (student ID, name, year, major).
- Create a tuple
student
containing(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