Tuples in Python: Immutable Collections You Can Rely On
In Python, a tuple is a collection data type that groups multiple values together. Tuples are similar to lists but with one key difference: tuples are immutable, meaning once you create them, you cannot change their content.
What Is a Tuple?
-
An ordered collection of elements.
-
Elements can be of any type: numbers, strings, objects, even mixed types.
-
Defined using parentheses
( )or sometimes just commas. -
Immutable: no adding, removing, or changing elements after creation.
Creating Tuples
Why Use Tuples?
-
Data integrity: Prevent accidental changes to data.
-
Performance: Tuples are generally faster and use less memory than lists.
-
Dictionary keys: Tuples can be used as keys in dictionaries (lists cannot).
-
Function returns: Often used to return multiple values from functions.
Accessing Tuple Elements
You access elements by index, starting at 0:
❌ What You Can’t Do with Tuples
Since tuples are immutable, these will raise errors:
Tuple Operations
Though immutable, you can do these with tuples:
-
Concatenation: Combine tuples with
+
-
Repetition: Repeat tuples with
*
-
Membership check:
️ Useful Tuple Methods
Tuples have only two built-in methods:
-
.count(value)— counts how many times a value appears.
-
.index(value)— returns the first index of a value.
Tuple Unpacking
You can assign tuple values to variables in one line:
This makes code cleaner and easier to read.
Summary
| Feature | Description |
|---|---|
| Definition | Ordered, immutable collection |
| Syntax | Parentheses ( ) or commas |
| Mutability | Immutable (cannot change) |
| Use cases | Fixed data, dictionary keys, multiple returns from functions |
| Access | By index, like lists |
