Change language

Split nested list into two lists in Python

Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist.

Split nested list into two lists using map, zip()

# Python code to demonstrate
# splitting nested list
# into 2 lists
  
# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
  
# printing initial lists
print ("initial list", str(ini_list))
  
# code to split it into 2 lists
res1, res2 = map(list, zip(*ini_list))
  
# printing result
print("final lists", res1, "
", res2)

Output:

initial list [[1, 2], [4, 3], [45, 65], [223, 2]]
final lists [1, 4, 45, 223] 
 [2, 3, 65, 2]

Suppose we have a list of lists i.e.

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]

This list contains 3 different lists of integers. We want to convert this list of lists to a single flat list, which should only contain integers like,

[1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

We’re going to use list comprehension to iterate over a list of lists, and then for each internal list, iterate over the individual items in that list again. Then add these items to a new list, i.e.

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]
# Use list comprehension to convert a list of lists to a flat list 
flatList = [ item for elem in listOfList for item in elem]
print(’Flat List : ’, flatList)        

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

Although this is a single line solution but this kind of coding is not easy to maintain.


Use list.extend() to convert a list of lists to a flat list

In python list data type provides a method to add all the contents of an iterable to the existing list, list.extend(iterable)

It extends the existing list object by appending all the contents of given iterable. Let’s use this to convert list of lists to a flat list,

# List of list
listOfList = [ [1, 2, 3, 4, 5],
                [11, 22, 33, 44, 55],
                [17, 18, 19, 20, 21] ]
flatList = []
for elem in listOfList:
    flatList.extend(elem)
print(’Flat List : ’, flatList)

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

Use list.append() to convert a list of lists to a flat list

In python list data type provides a method to add an item at the end of a list,

list.append(x)

Let’s use this to convert list of lists to a flat list,
flatList = []
for elem in listOfList:
    for item in elem:
        flatList.append(item)
print(’Flat List : ’, flatList)            

Output:

Flat List :  [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]

Splitting a nested list into two lists

StackOverflow question

I have a nested list like this:

    my_list = [[1320120000000, 48596281], [1320206400000, 48596281], [1320292800000, 50447908]]

I would like to split it into something that looks like this:

    my_list1 = [48596281, 48596281, 50447908] 
    my_list2 = [1320120000000, 1320206400000, 1320292800000]    

I know that this is fairly simple, but I haven’t been able to get it to work. Any help would be much appreciated.

Answer:

This is what the builtin function zip is for.

my_list2, my_list1 = zip(*my_list)

If you want lists instead of tuples, you can do

my_list2, my_list1 = map(list, zip(*my_list))

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically