How to Transpose a List of Lists (2D List) in Python
This article explains how to transpose a list of lists (i.e., a 2D list) in Python.
If you don’t want to import NumPy or pandas just to transpose a list, you can use the built-in zip()
function instead.
For example, consider the following list of lists:
import numpy as np
import pandas as pd
l_2d = [[0, 1, 2], [3, 4, 5]]
Convert to numpy.ndarray
and transpose with T
Convert the original list of lists into a NumPy array (numpy.ndarray
), then transpose it using the T
attribute.
If you want the result as a regular Python list
, simply call the tolist()
method.
arr_t = np.array(l_2d).T
print(arr_t)
print(type(arr_t))
# [[0 3]
# [1 4]
# [2 5]]
# <class 'numpy.ndarray'>
l_2d_t = np.array(l_2d).T.tolist()
print(l_2d_t)
print(type(l_2d_t))
# [[0, 3], [1, 4], [2, 5]]
# <class 'list'>
Alternatively, you can use the transpose()
method of ndarray
or the standalone numpy.transpose()
function. Refer to the following article for details.
Convert to pandas.DataFrame
and transpose with T
Convert the original list of lists into a pandas.DataFrame
, then transpose it using the T
attribute.
To get a list
, first extract the underlying numpy.ndarray
using the values
attribute, then convert it with the tolist()
method.
df_t = pd.DataFrame(l_2d).T
print(df_t)
print(type(df_t))
# 0 1
# 0 0 3
# 1 1 4
# 2 2 5
# <class 'pandas.core.frame.DataFrame'>
l_2d_t = pd.DataFrame(l_2d).T.values.tolist()
print(l_2d_t)
print(type(l_2d_t))
# [[0, 3], [1, 4], [2, 5]]
# <class 'list'>
Transpose with built-in zip()
function
You can also use the built-in zip()
function to transpose a list of lists.
The zip()
function returns an iterator that combines multiple iterables, such as lists and tuples.
To use it for transposition, unpack the original list using the *
operator. This passes each inner list as a separate argument to zip()
.
l_2d_t_tuple = list(zip(*l_2d))
print(l_2d_t_tuple)
print(type(l_2d_t_tuple))
# [(0, 3), (1, 4), (2, 5)]
# <class 'list'>
print(l_2d_t_tuple[0])
print(type(l_2d_t_tuple[0]))
# (0, 3)
# <class 'tuple'>
The result is a list of tuples. To convert it into a list of lists, use a list comprehension with list()
.
l_2d_t = [list(x) for x in zip(*l_2d)]
print(l_2d_t)
print(type(l_2d_t))
# [[0, 3], [1, 4], [2, 5]]
# <class 'list'>
print(l_2d_t[0])
print(type(l_2d_t[0]))
# [0, 3]
# <class 'list'>
Here's a breakdown: the list is unpacked using *
, passed to zip()
, and the resulting tuples are converted into lists using a list comprehension.
print(*l_2d)
# [0, 1, 2] [3, 4, 5]
print(list(zip([0, 1, 2], [3, 4, 5])))
# [(0, 3), (1, 4), (2, 5)]
print([list(x) for x in [(0, 3), (1, 4), (2, 5)]])
# [[0, 3], [1, 4], [2, 5]]