04-25-2020, 06:08 AM
Convert Tuple to List
Problem: Given a Python tuple with elements. How to convert it into a list with the same elements?
Examples:
Note Tuple: Tuples are similar to lists—with the difference that you cannot change the tuple values (tuples are immutable) and you use parentheses rather than square brackets.
Solution: Use the built-in Python function to convert a list into a tuple. You don’t need to import any external library.
Code: The following code converts the three given tuples into lists.
Try It Yourself: With our interactive code shell, you can try it yourself. As a small exercise, try to convert the empty tuple into a list and see what happens.
https://repl.it/@finxter/tupletolist?lite=true
Explanation: You can see that converting a tuple with one element leads to a list with one element. The function is the easiest way to convert a tuple into a list. Note that the values in the tuple are not copied—only a new reference to the same element is created:
![[Image: list_to_tuple-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/04/list_to_tuple-1024x576.jpg)
The graphic also shows how to convert a tuple back to a list by using the function (that’s also a Python built-in function). Thus, calling on a list will result in a new list with the same elements.
Related articles:
Try to execute this code with the interactive Python tutor:
https://pythontutor.com/iframe-embed.htm...nces=false
Problem: Given a Python tuple with
Code:
nCode:
nExamples:
- Convert tuple into listCode:
(1, 2, 3, 4, 5).Code:[1, 2, 3, 4, 5]
- Convert tuple into listCode:
('Alice', 'Bob', 'Ann').Code:['Alice', 'Bob', 'Ann']
- Convert tuple into listCode:
(1,).Code:[1]
Note Tuple: Tuples are similar to lists—with the difference that you cannot change the tuple values (tuples are immutable) and you use parentheses rather than square brackets.
Solution: Use the built-in Python
Code:
list()Code: The following code converts the three given tuples into lists.
Code:
tuple_1 = (1, 2, 3, 4, 5)
print(list(tuple_1))
# [1, 2, 3, 4, 5] tuple_2 = ('Alice', 'Bob', 'Ann')
print(list(tuple_2))
# ['Alice', 'Bob', 'Ann'] tuple_3 = (1,)
print(list(tuple_3))
# [1]Try It Yourself: With our interactive code shell, you can try it yourself. As a small exercise, try to convert the empty tuple
Code:
()https://repl.it/@finxter/tupletolist?lite=true
Explanation: You can see that converting a tuple with one element leads to a list with one element. The
Code:
list()![[Image: list_to_tuple-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/04/list_to_tuple-1024x576.jpg)
The graphic also shows how to convert a tuple back to a list by using the
Code:
tuple()Code:
list(tuple(lst))Code:
lstRelated articles:
Try to execute this code with the interactive Python tutor:
https://pythontutor.com/iframe-embed.htm...nces=false

