Open In App

Python | Split nested list into two lists

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. In this article, we will see how to split nested lists into two lists in Python.

Python Split Nested List into Two Lists

Below are the ways by which we can split nested lists into two lists in Python:

Split Nested List into Two Lists with map and zip()

In this example, the Python code starts with the nested list ini_list and splits it into two separate lists, res1 and res2, using the zip function along with map and list conversions. The output displays the initial nested list and the two resulting lists.

Python3




# 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, "\n", res2)


Output

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

Time complexity: O(n)
Auxiliary Space: O(n)

Python Split Nested List into Two Lists Using List Comprehension

In this example, the Python code initializes a nested list ini_list and then splits it into two separate lists, res1 and res2, by extracting the second and first elements of each inner list, respectively. The output displays the initial nested list and the two resulting lists.

Python3




# 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 = [i[1] for i in ini_list]
res2 = [i[0] for i in ini_list]
 
# printing result
print("final lists", str(res1), "\n", str(res2))


Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Split Nested List into Two Lists with operator.itemgetter() 

In this example, the Python code initializes a nested list ini_list and splits it into two separate lists, res1 and res2, using the itemgetter function from the operator module to extract the first and second elements of each inner list, respectively.

Python3




from operator import itemgetter
 
# 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 = list(map(itemgetter(0), ini_list))
res2 = list(map(itemgetter(1), ini_list))
 
# printing result
print("final lists", str(res1), "\n", str(res2))


Output

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

Time complexity: O(n)
Auxiliary Space: O(n)

Python Split Nested List into Two Lists Using extend() Method

In this example, the Python code initializes a nested list ini_list and splits it into two separate lists, res1 and res2, by flattening the inner lists and then alternately distributing their elements into the two resulting lists based on their index positions.

Python3




# initialising nested lists
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
 
# printing initial lists
print("initial list", str(ini_list))
x = []
for i in ini_list:
    x.extend(i)
res1 = []
res2 = []
for i in range(0, len(x)):
    if(i % 2 == 0):
        res1.append(x[i])
    else:
        res2.append(x[i])
# printing result
print("final lists", str(res1), "\n", str(res2))


Output

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

Time Complexity: O(n), where n is length of x list.
Auxiliary Space: O(n+m), where n is length of res1 list and m is length of res2 list.

Split Nested List into Two Lists Using itertools

In this example, the Python code initializes a nested list ini_list and splits it into two separate lists, res1 and res2, using the itertools.zip_longest function to pair elements from the inner lists. The output displays the initial nested list and the two resulting lists, where missing values are filled with an empty string.

Python3




import itertools
 
# 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 = list(itertools.zip_longest(*ini_list, fillvalue=''))
res1, res2 = list(res1), list(res2)
# printing result
print("final lists", str(res1), "\n", str(res2))
# This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n)
Auxiliary Space: O(n)

Python Split Nested List into Two Lists Using numpy.transpose()

In this example, the Python code initializes a nested list ini_list and converts it into a NumPy array (np_arr). It then transposes the NumPy array (tr_np_arr) and converts it back to two separate lists, res1 and res2.

Python3




# importing required module
import numpy as np
 
# initialising nested list
ini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]
 
# printing initial list
print("Initial List: ", ini_list)
 
# Converting nested list to numpy array
np_arr = np.array(ini_list)
 
# Transposing numpy array
tr_np_arr = np.transpose(np_arr)
 
# Converting transposed numpy array to list
res1, res2 = tr_np_arr.tolist()
 
# printing result
print("Final lists: ", res1, "\n", res2)


Output:

Initial List: [[1, 2], [4, 3], [45, 65], [223, 2]]
Final lists: [1, 4, 45, 223]
[2, 3, 65, 2]

Time complexity: O(n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Python Program to Split the Even and Odd elements into two different lists
In this program, a list is accepted with a mixture of odd and even elements and based on whether the element is even or odd, it is Split the Even and Odd elements using Python. Examples Input: [8, 12, 15, 9, 3, 11, 26, 23] Output: Even lists: [8, 12, 26] Odd lists: [15, 9, 3, 11, 23] Input: [2, 5, 13, 17, 51, 62, 73, 84, 95] Output: Even lists: [2,
2 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Split list into lists by particular value
In Python, To split a list into sublists based on a particular value. The idea is to iterate through the original list and group elements into sub-lists whenever the specified value is encountered. It is often necessary to manipulate and process lists, especially when dealing with large amounts of data. One frequent operation is dividing a list int
5 min read
Split a Python List into Sub-Lists Based on Index Ranges
Given a list of lists and a list of length, the task is to split the list into sublists based on the Index ranges. In this article, we will see how we can split list into sub-lists based on index ranges in Python. Split a List into Sub-Lists Based on Index Ranges in PythonBelow are some of the ways by which we can split a list into sub-lists based
2 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Python | Convert given list into nested list
Sometimes, we come across data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to a nested list is quite common in web development. Let's discuss certain ways in which this can be performed. Convert the Given List into Nested List in PythonBelow are th
5 min read
Python - Nested Records List from Lists
Sometimes, while working with Python Data, we can have problems in which we have data incoming in different formats. In this, we can receive data as key and value in separate dictionaries and we are required to make values as list of records with a new key. Let's discuss certain ways in which we can convert nested record lists from lists. Nested Li
6 min read
Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to split string around a passed separator or delimiter. After that, the string can be stored as a list in a seri
3 min read
Practice Tags :