How do you convert a list to a tuple in Python?

How do you convert a list to a tuple in Python?

Here are five examples demonstrating how to convert a list to a tuple in Python:

  1. Basic Conversion:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (1, 2, 3, 4, 5)
  1. 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)
  1. 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)
  1. Empty List to Tuple:
my_list = []
my_tuple = tuple(my_list)
print(my_tuple)  # Output: ()
  1. 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.