Here are five examples demonstrating how to convert a list to a tuple in Python:
- Basic Conversion:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
- List Comprehension:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(item for item in my_list)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
- Conversion with Mixed Data Types:
my_list = [1, 'hello', 3.14, True]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 'hello', 3.14, True)
- Empty List to Tuple:
my_list = []
my_tuple = tuple(my_list)
print(my_tuple) # Output: ()
- Nested List to Tuple:
my_list = [[1, 2], [3, 4], [5, 6]]
my_tuple = tuple(my_list)
print(my_tuple) # Output: ([1, 2], [3, 4], [5, 6])
These examples showcase various scenarios for converting a list to a tuple, including basic conversion, list comprehension, handling mixed data types, dealing with an empty list, and converting a nested list.