Python | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that first list contains first elements of each sublists and second list contains second element of each sublists. Method #1: Using map, zip()
Python3
# Python code to demonstrate# splitting nested list# into 2 lists# initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]# printing initial listsprint ("initial list", str(ini_list))# code to split it into 2 listsres1, res2 = map(list, zip(*ini_list))# printing resultprint("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]
Method #2: Using list comprehension
Python3
# python code to demonstrate# splitting nested list# into 2 lists# initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]# printing initial listsprint ("initial list", str(ini_list))# code to split it into 2 listsres1 = [i[1] for i in ini_list]res2 = [i[0] for i in ini_list]# printing resultprint("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]
Method #3: Using operator.itemgetter()
Python3
# python code to demonstrate# splitting nested list# into 2 listsfrom operator import itemgetter# initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]# printing initial listsprint ("initial list", str(ini_list))# code to split it into 2 listsres1 = list(map(itemgetter(0), ini_list))res2 = list(map(itemgetter(1), ini_list))# printing resultprint("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]
Method #4 : Using extend() method
Python3
# python code to demonstrate# splitting nested list# into 2 lists# initialising nested listsini_list = [[1, 2], [4, 3], [45, 65], [223, 2]]# printing initial listsprint ("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 resultprint("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]


