![]() |
|
[Tut] Convert Tuple to List - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Convert Tuple to List (/thread-94722.html) |
[Tut] Convert Tuple to List - xSicKxBot - 04-25-2020 Convert Tuple to List Problem: Given a Python tuple with Code: nCode: nExamples:
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()![]() 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.html#code=list_1%20%3D%20%5B'Alice',%20'Bob',%20'Ann'%5D%0Atuple_1%20%3D%20tuple%28list_1%29%0Alist_2%20%3D%20list%28tuple_1%29%0A%0Aprint%28list_1%29%0Aprint%28tuple_1%29%0Aprint%28list_2%29%0A&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=6&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false |