List of Lists Python

Aisha Rajput
10 min readSep 25, 2022

--

#webdev #python #programming #beginners

A list is a mutable data type in python that is organized inside square brackets. This article is about the list of lists Python with examples.
A list of lists in Python means each element of a list is itself a list. A list contains lists as its elements of it.

Table Of Content

How to create a list of lists in Python?

To Enclose multiple lists as an item inside square brackets.
Suppose to create a nested list to add all lists as elements inside a list.
a = [1,2,3],b = [3,4,5],c = [6,7,8] => list_of_list [[1,2,3], [3,4,5], [6,7,8]]

How to make a list of lists from a single list in Python?

Use the abstract syntax Trees to convert the single list into a list of lists in python (Nested List)

import ast# List Initialization
list1 = ['1 , 2', '7 , 9', '34 , 98', '66 , 89347', '723, 54, 0']
# using ast to convert
ListOfLists = [list(ast.literal_eval(x)) for x in list1]
# printing
print(ListOfLists)

Output

[[1, 2], [7, 9], [34, 98], [66, 89347], [723, 54, 0]]

How to generate a list of lists

● Define blank list
● Define the range of the list of lists (item) from 0 to 3
● Create a sub-list inside every nested list of range from 1 to 5
● Print

listoflists = []
for i in range(0,3):
sublist = []
for j in range(1,5):
sublist.append((i,j))
listoflists.append(sublist)
print (listoflists)

Output

[[(0, 1), (0, 2), (0, 3), (0, 4)], [(1, 1), (1, 2), (1, 3), (1, 4)], [(2, 1), (2, 2), (2, 3), (2, 4)]]

How to convert multiple lists into a list of lists

Call the multiple lists inside the square brackets with lists name that will embed the multiple lists into a lists

list1=[1,2]
list2=[3,4]
list3=[4,5,6]
print("List 1:" +str(list1))
print("List 2:" +str(list2))
print("List 3:" +str(list3))
listoflists=[list1, list2, list3]
print ("List of lists"+str(listoflists))

Output

List 1:[1, 2]
List 2:[3, 4]
List 3:[4, 5, 6]
List of lists[[1, 2], [3, 4], [4, 5, 6]]

How to convert the list of lists into a NumPy array

Import NumPy library that converts a list of lists into a 2-Dimensional array in Python.

# Import the NumPy library
import numpy as nmp
# Create the list of lists
list_of_lists = [['x', 'y', 'z'], [4, 5, 6], [7, 8, 9]]
# Convert it to an array
arr = nmp.array(list_of_lists)
# Print as array
print(arr)

output

[['x' 'y' 'z']
['4' '5' '6']
['7' '8' '9']]

How to convert into a list of lists to string in python

● Define the lists of characters in a list
● Use the join method that connects each character of a defined list
● Map the two lists as two words

# Convert List of lists to Stringsa= [["M", "y"],["C", "o", "d", "e"]]
res = list(map(''.join, a))
print(*res, sep=" ")

output

My Code

How to convert into a list of lists to set in python

● Use the map method with a set function that removes duplicate items from the list.
● print list of lists as set in python.

# Convert List of lists to Seta= [[1,2,3,4],["a", "a", "b", "e"],["Sam", "John"]]
res = list(map(set,a))
print(*res, sep=" ")

Output

{1, 2, 3, 4} {'b', 'a', 'e'} {'Sam', 'John'}

How to convert set to list of lists in python

● Use the comprehension method that iterates each object of the set sequentially
● Use “list” to convert a defined set into a list
● n defined the number of nested lists.
● Print a Python list of lists with the help of the comprehension method.

my_set = set({1, 4, 2, 3, 5, 6, 7, 8,})
l = list(my_set)
n = 3
# using list comprehension
x = [l[i:i + n] for i in range(0, len(l), n)]
print(x)

Output

[[1, 2, 3], [4, 5, 6], [7, 8]]

How to convert a list of lists to a List of tuples in python

Tuples stores data in an ordered form.
● Use map function with built-in tuple method to convert the list of lists into tuple in python.

a= [[1,2,3,4],["a", "a", "b", "e"],["Sam", "John", "Morgan"]]
tuples = list(map(tuple, a))
print(tuples)

output

[(1, 2, 3, 4), ('a', 'a', 'b', 'e'), ('Sam', 'John', 'Morgan')]

How to Convert List of Tuples to List of Lists in Python?

Perform the reverse operation to convert tuples into the list of lists.
● Use the built-in list function to convert a list of tuples into a list of lists.
● For loop iterate each element of tuple and print as a nested list.

tuples = [(1, 2, 3), (4, 5, 6), (90, 376, 84)]
lists = [list(a) for a in tuples]
print(lists)

output

[[1, 2, 3], [4, 5, 6], [90, 376, 84]]

How to convert a list of lists to Dataframe in python

DataFrame is a labeled data structure that is 2-Dimensional. It contains columns and rows that may contain different data types inside it.
● Import Pandas library to convert a list of lists to dataframe.
● Define a list of lists.
● Define columns name with the same length of list items. E.g., 3 columns name for 3 data inside the nested list
● Print as a column labeled data with index number automatically.

import pandas as pd
data = [['DSA', 'Python', 80],
['DS', 'MATLAB', 70],
['OSDC', 'C', 94],
['MAPD', 'JAVA', 78]]
df = pd.DataFrame(data, columns=['Subject', 'Language', 'Marks'])
print(df)

Output

Subject Language  Marks
0 DSA Python 80
1 DS MATLAB 70
2 OSDC C 94
3 MAPD JAVA 78

How to convert DataFrame to a list of lists

Perform the reverse function to convert the dataframe into the list of lists by using a built-in list function .

import pandas as pd
df = pd.DataFrame(
[['DSA', 'Python', 80],
['DS', 'MATLAB', 70],
['OSDC', 'C', 94],
['MAPD', 'JAVA', 78]], columns= ['Subject', 'Language', 'Marks'])
print ("DataFrame Output")
print(df)
def dfToTable(df:pd.DataFrame) -> list:
return [list(df.columns)] + df.values.tolist()
print("\n Convert DataFrame to list of lists :" +str(dfToTable(df)))

output

DataFrame Output
Subject Language Marks
0 DSA Python 80
1 DS MATLAB 70
2 OSDC C 94
3 MAPD JAVA 78
Convert DataFrame to list of lists :[['Subject', 'Language', 'Marks'], ['DSA', 'Python', 80], ['DS', 'MATLAB', 70], ['OSDC', 'C', 94], ['MAPD', 'JAVA', 78]]

How to convert a list of lists to Dictionary in python

Dictionary contains keys with their values in ordered form without duplication.
● Define a list of lists
● Use for loop to iterate key with index 0 and value with index 1 and print as a dictionary

a = [['samsung', 1],['OPPO', 3],['iPhone', 2], ['Huawei', 4]]
data_dict = {}
for x in a:
data_dict[x[0]] = x[1]
print(data_dict)

Output

{'samsung': 1, 'OPPO': 3, 'iPhone': 2, 'Huawei': 4}

How to convert a dictionary to a list of lists in python

● Define the dictionary with key and their values.
● Convert to list of lists with map and list function

dict = {'samsung': 1, 'OPPO': 3, 'iPhone': 2, 'Huawei': 4}
a= list(map(list, dict.items()))
print(a)

Output

[['samsung', 1], ['OPPO', 3], ['iPhone', 2], ['Huawei', 4]]

Sort a List of Lists in Python

Sort a list of lists in ascending order

Sort according to the first element of each nested list. It sorts the list according to the first value of each nested list. This method makes changes to the original list itself.

A = [[5, 90], [4, 89], [2, 70], [1, 0]]
print("Orignal List:" +str(A))
A.sort()
print("New sorted list A is: % s" % (A))

*Output *

Orignal List:[[5, 90], [4, 89], [2, 70], [1, 0]]
New sorted list A is: [[1, 0], [2, 70], [4, 89], [5, 90]]

Sort a list of lists in descending order

Use reverse sorting order to sort a list of lists in descending manner.

A = [[5, 90], [4, 89], [2, 70], [1, 0]]
print("Orignal List:" +str(A))
A.sort(reverse=True)
print("Descending/reverse sorted list A is: % s" % (A))

*Output *

Orignal List:[[5, 90], [4, 89], [2, 70], [1, 0]]
Descending/reverse sorted list A is: [[5, 90], [4, 89], [2, 70], [1, 0]]

Sort a list of lists by length

Sort a list of lists according to the length of each list. “len” function sorts the list with the long length first.

A = [[1, 2, 3, 4],['a', 'b', 'c', 'd'],[1, 5, 6, 'f', 'a']]
A.sort(key=len)
print(A)

output

[[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [1, 5, 6, 'f', 'a']]

Operations of a list of lists

Python Zip List of Lists

Define three lists and zipped them into a list of lists with the help of the zip method

Domain = ['Software', 'Networking', 'Telecommunication']
Students = [8345, 8437, 422]
Companies = ['Microsoft', 'CISCO', 'AT&T']
zipped = zip(Domain, Students, Companies)
print(list(zipped))

Output

[('Software', 8345, 'Microsoft'), ('Networking', 8437, 'CISCO'), ('Telecommunication', 422, 'AT&T')]

Python Unpack List of Lists

Use for loop with map and join function to unpack the zipped list of lists.

members= [('Software', 8345, 'Microsoft'), ('Networking', 8437, 'CISCO'), ('Telecommunication', 422, 'AT&T')]
for item in members:
print (' '.join(map(str, item)))

*Output *

Software 8345 Microsoft
Networking 8437 CISCO
Telecommunication 422 AT&T
In [ ]:

Transpose list of lists in Python

This method transposes the array to a list with the help of the NumPy library. This method changes the fashion of the array by taking 1st element of each list into 1st list, 2nd element of each array into the 2nd list, and 3rd element of each array into 3rd list in the output.

import numpy as np
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b= np.array(l).T.tolist()
print(b)

Output

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Append list of lists in python

Append is a built-in function of python programming that helps to append the additional sublist inside the list.

list1 = [["apple"], ["banana", "grapes"],["cherry", "guava"]]
AddList = [1, 2, 3]
list1.append(AddList)
print(list1)

Output

[['apple'], ['banana', 'grapes'], ['cherry', 'guava'], [1, 2, 3]]

Item inside sub list of a list

To append the additional item inside the list of lists with the help of the index value. e.g., a[2].append(4): append 4 in list number 2. ( index starts from 0)

a= [["apple"], ["banana", "grapes"] ,["cherry", "guava"]]
a[2].append(4)
print(a)

Output

[['apple'], ['banana', 'grapes'], ['cherry', 'guava', 4]]

Insert a list inside a list

Insert take two arguments. insert (position, item)
● the position where the list add. e.g., 2
● The item that adds to the list

a = [[1, 2], [3, 4],[5]]
print(a)
list1=[1, 2]
a.insert(2,list1)
print(a)

Output

[[1, 2], [3, 4], [5]]
[[1, 2], [3, 4], [1, 2], [5]]

Extend python list of lists

Use extend function to extend the number of lists inside a list

a = [['Samsung', 'Apple']]
b = [[6, 0, 4, 1]]
a.extend(b)
print (a)

Output

[['Samsung', 'Apple'], [6, 0, 4, 1]]
In [ ]:

Pop list of lists

The pop method removes the item defined item in the index
● Define 3 lists.
● Convert into a list of lists
● Remove item that is on the position of index 1 from that index number is 2
Note: index number starting from 0

list1=[1,2]
list2=[3,4]
list3=[4,5,6]
listoflists=[list1, list2, list3]
print ("Orignal List of lists:"+str(listoflists))
listoflists[2].pop(1)
print ("Popped list:" +str(listoflists))

Output

Orignal List of lists:[[1, 2], [3, 4], [4, 5, 6]]
Popped list:[[1, 2], [3, 4], [4, 6]]

Concatenation list of lists in python

Concatenate a list of lists to convert into a single list, using the sum operation.
● Define the list of lists
● Use sum property to concatenate the lists

z = [["a","b"], ["c"], ["d", "e", "f"]]result = sum(z, [])
print(result)

Output

['a', 'b', 'c', 'd', 'e', 'f']

Remove the duplicate item from the list of lists

Except “set” property, there is another method that removes the duplicate item from the list of lists
Use gruopby of itertools that will sort the list of lists one by one and remove duplicate nested lists from the list.

import itertools
a = [[5, 8], [4], [5], [5, 6, 2], [1, 2], [3], [4], [5], [3]]
a.sort()
l= list(k for k,_ in itertools.groupby(a))
print(l)

output

[[1, 2], [3], [4], [5], [5, 6, 2], [5, 8]]

Print list of lists without brackets

This method converts and prints all the items of the list without square brackets and prints them as comma-separated values.

a=[["Cricket", 2], ["Football",6,  5], ["Tennis", 2], ["Hockey", 2] ]
for item in a:
print(str(item[0:])[1:-1])

output

'Cricket', 2
'Football', 6, 5
'Tennis', 2
'Hockey', 2
In [ ]:

Call the list of lists by using the index number

To access the particular list inside the list, use the list position as an index when calling the print command.
e.g. x [2]: item 3 of list x (index count start from 0)

x = [["a","b"], ["c"], ["d", "e", "f"]]
print(x[2])

Output

['d', 'e', 'f']

Access to the item of the list of lists in python

e.g. x [2][1]: element 2 of list 3 of list

x = [["a","b"], ["c"], ["d", "e", "f"]]
print(x[2][1])

Output

e

Delete the list of lists in python

Use del with position index that wants to delete and print a modified list of list.

x = [["a","b"], ["c"], ["d", "e", "f"]]
del x[1]
print(x)

Output

[['a', 'b'], ['d', 'e', 'f']]

Conclusion

In this article, we have tried to cover all the operations such as all types of Sorting of the list of lists, Conversion of the list of lists, deletion, insertion, extension, concatenation, append, etc.

--

--