1. What are Tuples? The Basics
A tuple is an ordered, immutable (unchangeable) collection of items. Key characteristics:
- Ordered: Items have a defined order, which remains constant. You can access items by their position (index).
- Immutable: This is the defining characteristic. Once created, you cannot change the values of its elements, add new elements, or remove existing ones.
- Allows Duplicates: Like lists, tuples can contain multiple items with the same value.
- Can Hold Mixed Data Types: A single tuple can contain integers, strings, floats, Booleans, and even other data structures (including mutable ones like lists).
Syntax: Tuples are typically created using parentheses `()` (though they are not strictly required for creation, just for clarity and in some specific cases). Items are separated by commas.
# An empty tuple
empty_tuple = ()
# Tuple of integers (e.g., RGB color values)
rgb_color = (255, 0, 128)
# Tuple of strings (e.g., UdaanPath modules)
modules = ("Python Basics", "DSA", "Web Development")
# Tuple with mixed data types (e.g., user profile)
user_profile = ("John Doe", 30, True, 75.5)
# Special case: single-element tuple (requires a comma!)
single_element_tuple = ("UdaanPath",) # The comma is crucial!
not_a_tuple = ("Just a string") # This is just a string in parentheses
print(f"Empty tuple: {empty_tuple}")
print(f"RGB Color: {rgb_color}")
print(f"Modules: {modules}")
print(f"User Profile: {user_profile}")
print(f"Single element tuple: {single_element_tuple}, Type: {type(single_element_tuple)}")
print(f"Not a tuple: {not_a_tuple}, Type: {type(not_a_tuple)}")
Empty tuple: () RGB Color: (255, 0, 128) Modules: ('Python Basics', 'DSA', 'Web Development') User Profile: ('John Doe', 30, True, 75.5) Single element tuple: ('UdaanPath',), Type: <class 'tuple'> Not a tuple: Just a string, Type: <class 'str'>