Skip to content

Convert Tuple to list Python | Example code

  • by

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

A simple example code initializes a tuple and converts it to a list using a 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

In the same way you can convert a Tuple of Integers to a 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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading