Understanding Python Tuples
Tuples are ordered, immutable collections of items in Python. They are similar to lists but cannot be changed after creation. Tuples are defined using parentheses ()
or simply by separating items with commas. They can contain elements of different data types, including other tuples.
Creating Tuples
Example 1: Creating Tuples with Different Data Types
# Creating tuples with different data types
empty_tuple = ()
single_item_tuple = (42,)
mixed_tuple = (1, "Hello", 3.14, True, None)
nested_tuple = ((1, 2), (3, 4), (5, 6))
print("Empty Tuple:", empty_tuple)
print("Single Item Tuple:", single_item_tuple)
print("Mixed Tuple:", mixed_tuple)
print("Nested Tuple:", nested_tuple)
Output
Empty Tuple: ()
Single Item Tuple: (42,)
Mixed Tuple: (1, 'Hello', 3.14, True, None)
Nested Tuple: ((1, 2), (3, 4), (5, 6))
Example 2: Creating Tuples Without Parentheses
# Creating tuples without parentheses
tuple_without_parentheses = 1, 2, 3
print("Tuple Without Parentheses:", tuple_without_parentheses)
print("Type:", type(tuple_without_parentheses))
Output
Tuple Without Parentheses: (1, 2, 3)
Type: <class 'tuple'>
Example 3: Creating a Tuple from an Iterable
# Creating a tuple from a list
list_data = ["Karthick AG", "Durai", "Vijay"]
tuple_from_list = tuple(list_data)
print("Tuple from List:", tuple_from_list)
Output
Tuple from List: ('Karthick AG', 'Durai', 'Vijay')
Explanation: Tuples can be created from any iterable using the tuple()
constructor. In the examples, we demonstrated different ways to create tuples, including empty tuples, single-item tuples (note the comma), and converting lists to tuples.