Convert Tuple to list Python | Example code

Use the built-in list() function to convert a tuple to a list in Python. Simply passes the given tuple as an argument to the function.

list(tuple)

Example Tuple to list Python

Simple example code initializes a tuple and converts it to a list using list(sequence).

# initialize tuple
aTuple = (True, 100, 'John')

# tuple to list
aList = list(aTuple)

# print list
print(type(aList))
print(aList)

Output:

Convert Tuple to list Python

Another Example

The same way you can convert Tuple of Integers to List

aTuple = (1, 2, 3)

aList = list(aTuple)

print(aList)

Output: [1, 2, 3]

Complex tuple to list

my_tuple = (('7578',), ('6052',), ('8976',), ('9946',))

result = [int(x) for x, in my_tuple]

print(result)

Output: [7578, 6052, 8976, 9946]

Source: stackoverflow.com/

Other methods: Convert list of tuples into list

Using list comprehension, itertools, iteration, sum, operator + reduce, and lambda.

import itertools
from functools import reduce
import operator

lt = [('A', 2), ('B', 4), ('C', '6')]

# list comprehension
lc = [item for t in lt for item in t]
print(lc)

# Using itertools
it = list(itertools.chain(*lt))
print(it)

# iteration
res = []
for t in lt:
    for x in t:
        res.append(x)

print(res)

# using sum function()
sl = list(sum(lt, ()))
print(sl)

# operator and reduce
print(list(reduce(operator.concat, lt)))

Output:

[‘A’, 2, ‘B’, 4, ‘C’, ‘6’]
[‘A’, 2, ‘B’, 4, ‘C’, ‘6’]
[‘A’, 2, ‘B’, 4, ‘C’, ‘6’]
[‘A’, 2, ‘B’, 4, ‘C’, ‘6’]
[‘A’, 2, ‘B’, 4, ‘C’, ‘6’]

Lambda example

lt = [('A', 2), ('B', 4), ('C', '6')]

# Using map for 0 index
b = map(lambda x: x[0], lt)

# Using map for 1 index
c = map(lambda x: x[1], lt)

# converting to list
b = list(b)
c = list(c)

# Combining output
out = b + c

# printing output
print(out)

Output: [‘A’, ‘B’, ‘C’, 2, 4, ‘6’]

Do comment if you have any doubts and suggestions on this Python tuple list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.