Python Tuples
Table of Contents
Description
A tuple in Python is an ordered, immutable (unchangeable), and heterogeneous collection of elements. Tuples are defined using parentheses () and are similar to lists, but once created, their contents cannot be altered.
They are often used to group related pieces of data and are hashable, meaning they can be used as keys in dictionaries or elements in sets (unlike lists).
Prerequisites
- Understanding of basic Python data types.
- Familiarity with lists for comparison.
Examples
Here's a simple program in Python:
# Creating a tuple coordinates = (10.5, 20.3) # Tuple with multiple data types person = ("Alice", 30, "Engineer") # Accessing tuple elements by index print(coordinates[0]) # Output: 10.5 # Slicing a tuple print(person[1:]) # Output: (30, 'Engineer') # Nesting tuples nested = (1, (2, 3), 4) print(nested[1][1]) # Output: 3 # Tuple unpacking name, age, job = person print(name) # Output: 'Alice' # Singleton tuple (must include a comma) single = (5,) # This is a tuple not_a_tuple = (5) # This is an integer # Length of a tuple print(len(coordinates)) # Output: 2Real-World Applications
Returning multiple values from a function.
Grouping and storing read-only data.
Using as keys in dictionaries.
Iterating over fixed sets of values.
Representing points or coordinates.
Where topic Can Be Applied
Data science: Storing feature-label pairs.
Databases: Representing rows of immutable data.
Web development: Representing user session metadata.
Networking: Representing immutable configurations (e.g., IP, port).
Games: Storing positions or static states.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is a tuple in Python?
How are tuples different from lists?
Can a tuple contain mutable elements?
How do you create a tuple with one element?
Why are tuples considered more secure or faster than lists?