Tuples
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Tuples
Definition: Tuples are ordered collections used to store multiple items in a single variable. They are very similar to lists, but with one major difference: they are immutable, meaning they cannot be changed after creation.
Why: Beginner Python guides usually teach tuples right after lists to highlight the difference between data that can change (mutable) and data that must stay constant (immutable). They are used to protect data from accidental modifications.
Syntax
tuple_name = (item1, item2, item3)
Example
days = ("Mon", "Tue", "Wed")
print(days)
print(days[1])
Explanation
- Parentheses: Tuples are defined using round brackets
( )instead of square brackets. - Indexing: Just like lists, items inside a tuple have an order and can be accessed using their index number starting at
0(sodays[1]prints "Tue"). - Immutability: If you try to add or change an item (e.g.,
days[0] = "Sunday"), Python will throw an error.
Key Notes
- Tuples allow duplicate values (e.g., you can have
("Mon", "Tue", "Mon")). - Because they cannot change, tuples are faster and use less memory than lists.
- To create a tuple with only one item, you must include a trailing comma (e.g.,
my_tuple = ("apple",)), otherwise Python will mistake it for a regular string or number.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute