Borislav Hadzhiev
Last updated: Jul 3, 2022
Check out my new book
To convert a list of lists to two lists:
zip()
function with the *
operator to unzip the list.map()
function to convert the tuples in the zip
object to lists.list()
class to convert the map
object to a list.list_of_lists = [[1, 2], [3, 4], [5, 6]] result = list(map(list, zip(*list_of_lists))) # 👇️ [[1, 3, 5], [2, 4, 6]] print(result) first, second = result print(first) # 👉️ [1, 3, 5] print(second) # 👉️ [2, 4, 6]
The first step is to use the zip()
function with the *
(iterable unpacking)
operator to unzip the list.
list_of_lists = [[1, 2], [3, 4], [5, 6]] result = list(zip(*list_of_lists)) # 👇️ [(1, 3, 5), (2, 4, 6)] print(result)
The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.
The zip
function returns an iterator of tuples.
We used the map()
function to convert the tuples in the iterator to lists.
list_of_lists = [[1, 2], [3, 4], [5, 6]] result = list(map(list, zip(*list_of_lists))) # 👇️ [[1, 3, 5], [2, 4, 6]] print(result) first, second = result print(first) # 👉️ [1, 3, 5] print(second) # 👉️ [2, 4, 6]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
We simply passed each tuple in the iterator object to the list()
class.
The last step is to pass the map
object to the list()
class.
You can optionally unpack the list values into variables.
An alternative to consider is using multiple list comprehensions.
list_of_lists = [[1, 2], [3, 4], [5, 6]] a = [l[0] for l in list_of_lists] print(a) # 👉️ [1, 3, 5] b = [l[1] for l in list_of_lists] print(b) # 👉️ [2, 4, 6]
On each iteration, we access the current nested list
object at a specific
index and get a list containing the results.
Alternatively, you can use a list comprehension for the conversion.
To convert a list of lists to two lists:
zip()
function with the *
operator to unzip the list.zip
object.list()
class to convert each tuple to a list.list_of_lists = [[1, 2], [3, 4], [5, 6]] result = [list(tup) for tup in zip(*list_of_lists)] print(result) # 👉️ [[1, 3, 5], [2, 4, 6]] first, second = result print(first) # 👉️ [1, 3, 5] print(second) # 👉️ [2, 4, 6]
We used a list comprehension instead of using the map()
function.
On each iteration, we pass the current tuple to the list()
class to convert it
to a list.
Which approach you pick is a matter of personal preference. I'd go with the list comprehension as I find it more direct and easier to read.