List of Lists Python
Tags: webdev, python, programming, beginners
Published: 2022-09-24 03:31:24



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 the elements of it. 

## Table Of Content



* [How to create a list of lists in Python?] (#Q1)
* [How to make a list of lists from a single list in Python?] (#Q2)
* [How to generate a list of lists] (#Q3)
* [How to convert multiple lists into a list of lists] (#Q4)
* [How to convert the list of lists into a NumPy array] (#Q5)
* [How to convert into a list of lists to string in python] (#Q6)
* [How to convert into a list of lists to set in python] (#Q7)
* [How to convert set to list of lists in python] (#Q8)
* [How to convert a list of lists to a List of tuples in python] (#Q9)
* [How to Convert List of Tuples to List of Lists in Python?] (#Q10)
* [How to convert a list of lists to Dataframe in python] (#Q11)
* [How to convert DataFrame to a list of lists] (#Q12)
* [How to convert a list of lists to Dictionary in python] (#Q13)
* [How to convert a dictionary to a list of lists in python] (#Q14)
* [Sort a List of Lists in Python] (#Q15)
* [Sort a list of lists in ascending order] (#Q16)
* [Sort a list of lists in descending order] (#Q17)
* [Sort a list of lists by length] (#Q18)
* [Operations of a list of lists] (#Q19)
* [Python Zip List of Lists] (#Q20)
* [Python Unpack List of Lists] (#Q21)
* [Transpose list of lists in Python] (#Q22)
* [Append list of lists in python] (#Q23)
* [Item inside sub list of a list] (#Q24)
* [Insert a list inside a list] (#Q25)
* [Extend python list of lists] (#Q26)
* [Pop list of lists] (#Q27)
* [Concatenation list of lists in python] (#Q28)
* [Remove the duplicate item from the list of lists] (#Q29)
* [Print list of lists without brackets] (#Q30)
* [Call the list of lists by using the index number] (#Q31)
* [Access to the item of the list of lists in python] (#Q32)
* [Delete the list of lists in python] (#Q33)
* [Conclusion] (#Q34)




###How to create a list of lists in Python? <a name = Q1></a>
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? <a name = Q2></a>
Use the abstract syntax Trees to convert the single list into a list of lists in python (Nested List)

```python
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 <a name = Q3></a>
●	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



```python
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 <a name = Q4></a>
Call the multiple lists inside the square brackets with lists name that will embed the multiple lists into a lists



```python
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 <a name = Q5></a>

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

```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 <a name = Q6></a>
●	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



```python
# Convert List of lists to Strings

a= [["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 <a name = Q7></a>
●	Use the map method with a set function that removes duplicate items from the list.
●	print list of lists as set in python.


```python 
# Convert List of lists to Set

a= [[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 <a name = Q8></a>
●	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.

```python
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 <a name = Q9></a>
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.

```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? <a name = Q10></a>
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.

```python
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 <a name = Q11></a>
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.

```python
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 <a name = Q12></a>
Perform the reverse function to convert the dataframe into the list of lists by using a built-in list function .

```python
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 <a name = Q13></a>
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


```python
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 <a name = Q14></a>
●	Define the dictionary with key and their values.
●	Convert to list of lists with map and list function

```python
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<a name = Q15></a>
### Sort a list of lists in ascending order <a name = Q16></a>
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. 

```python
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 <a name = Q17></a>
Use reverse sorting order to sort a list of lists in descending manner. 

```python
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 <a name = Q18></a>
Sort a list of lists according to the length of each list. “len” function sorts the list with the long length first.

```python
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 <a name = Q19></a>

###Python Zip List of Lists <a name = Q20></a>
Define three lists and zipped them into a list of lists with the help of the zip method

```python
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 <a name = Q21></a>
Use for loop with map and join function to unpack the zipped list of lists.

```python
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 <a name = Q22></a>
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.

```python
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 <a name = Q23></a>

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

```python
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 <a name = Q24></a>
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)

```python
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 <a name = Q25></a>
Insert take two arguments. insert (position, item)
●	the position where the list add. e.g., 2
●	The item that adds to the list 

```python
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 <a name = Q26></a>
Use extend function to extend the number of lists inside a list

```python
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 <a name = Q27></a>
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**

```python
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 <a name = Q28></a>
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

```python
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 <a name = Q29></a>
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.


```python
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 <a name = Q30></a>
This method converts and prints all the items of the list without square brackets and prints them as comma-separated values.

```python
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 <a name = Q31></a>
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)

```python
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 <a name = Q32></a>
 e.g. x [2][1]: element 2 of list 3 of list

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

**Output**

```
e
```
###Delete the list of lists in python <a name = Q33></a>
Use del with position index that wants to delete and print a modified list of list.

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

**Output**

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

```

###Conclusion <a name = Q34></a>
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.