Python | Convert list of tuples to list of list (original) (raw)

Last Updated : 27 Dec, 2024

Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples.

Using numpy

NumPy makes it easy to convert a list of tuples into a list of lists in Python. This conversion is efficient and quick, especially when working with large datasets.

Example:

Python `

import numpy as np a= [(1, 2), (3, 4), (5, 6)]

Convert to numpy array and back to list

res = np.array(a).tolist() print(res)

`

Output

[[1, 2], [3, 4], [5, 6]]

**Explanation:

Let's understand different method to convert list of tuples to list of list.

Table of Content

Using List Comprehension

List comprehension offers concise and efficient way to convert list of tuples into list of lists in Python. This method is ideal for small to medium-sized datasets due to its readability and speed.

**Example:

Python `

a= [(1, 2), (3, 4), (5, 6)]

Convert tuples to lists

res = [list(i) for i in a] print(res)

`

Output

[[1, 2], [3, 4], [5, 6]]

**Explanation:

Using map()

map() applies the list() function to each tuple in list, converting them into lists efficiently. This method is ideal for transforming a list of tuples into list of lists in Python.

**Example:

Python `

a= [(1, 2), (3, 4), (5, 6)]

Convert each tuple in the list to a list

res = list(map(list, a)) print(res)

`

Output

[[1, 2], [3, 4], [5, 6]]

**Explanation:

itertools.starmap() is an alternative to map(), applying a function to each tuple in the list with argument unpacking. It's an effective but slightly less efficient method to convert list of tuples into list of lists.

Python `

import itertools a = [(1, 2), (3, 4), (5, 6)]

Convert each tuple to a list using starmap

res = list(itertools.starmap(lambda *x: list(x), a)) print(res)

`

Output

[[1, 2], [3, 4], [5, 6]]

**Explanation:

Using for Loop

Using for loop is a simple method to convert list of tuples into list of lists. However, it is less efficient for large datasets due to explicit iteration and repeated append operations.

**Example:

Python `

a= [(1, 2), (3, 4), (5, 6)] res = []

Iterate through each tuple in the list 'a'

for i in a: # Convert each tuple to a list and append it to res res.append(list(i)) print(res)

`

Output

[[1, 2], [3, 4], [5, 6]]

**Explanation:

Similar Reads