Here are five examples demonstrating, how to convert a tuple to a list in Python:
- Using the
list()
constructor:
# Original tuple
tuple1 = (1, 2, 3, 4, 5)
# Converting tuple to list
list1 = list(tuple1)
print(list1) # Output: [1, 2, 3, 4, 5]
- Using list comprehension:
# Original tuple
tuple2 = ('a', 'b', 'c', 'd', 'e')
# Converting tuple to list using list comprehension
list2 = [item for item in tuple2]
print(list2) # Output: ['a', 'b', 'c', 'd', 'e']
- Using the
extend()
method:
# Original tuple
tuple3 = (10, 20, 30, 40, 50)
# Creating an empty list
list3 = []
# Extending the list with elements from the tuple
list3.extend(tuple3)
print(list3) # Output: [10, 20, 30, 40, 50]
- Using the
+
operator:
# Original tuple
tuple4 = ('x', 'y', 'z')
# Converting tuple to list using the + operator
list4 = list(tuple4)
print(list4) # Output: ['x', 'y', 'z']
- Using the
map()
function:
# Original tuple
tuple5 = (100, 200, 300, 400, 500)
# Converting tuple to list using the map() function
list5 = list(map(str, tuple5))
print(list5) # Output: ['100', '200', '300', '400', '500']
These examples demonstrate different approaches to convert a tuple to a list in Python, including using the list()
constructor, list comprehension, the extend()
method, the +
operator, and the map()
function.