89DEVs

Python: How to convert tuple to list?

How to convert a tuple to a list in Python?

To convert a tuple to a list in Python, use the built-in list() function as shown below.

tuple to list

# convert tuple to list myTuple = (1, 2, 3) myList = list(myTuple) print(myList) The tuple is converted to a new list, using the list() function. Then the list is printed and it contains all values of the tuple. [1, 2, 3]

nested tuple to list

To convert a nested tuple to a list, use the list() function. Notice that only the outer tuple is converted to a list. The inner tuples remain as tuple type. # convert nested tuple to list myTuple = ((1, 2), (3, 4), (5, 6)) myList = list(myTuple) print(myList) The outer tuple is converted to a list, the inner tuples remain tuples. [(1, 2), (3, 4), (5, 6)]

convert inner tuples of nested tuples to list

To convert the inner tuples to lists as well, use list comprehension. Another quick workaround is to use the json module as shown below. # convert inner tuples in nested tuple to list import json myTuple = ((1, 2), (3, 4), (5, 6)) myList = json.loads(json.dumps(myTuple)) print(myList) The json module converts outer and inner tuples into a list. [[1, 2], [3, 4], [5, 6]]

                
        

Summary


Click to jump to section