Python: How to Create List of Lists (with examples)
The python programming language has many features built into it to make writing python code quick and easy. In this Python tutorial we are going to cover different ways to create a lists of lists as well as how to add new items to the contents of a list
Initialize the list directly
The simplest way to create a nested list in python is to just define all the lists then create a new list composeof the previously defined lists. However, if you have a variable number of items it is probably better to look at some of the different methods listed below
listOne = ["one", "two", "three"]
listTwo = ["four", "five", "six"]
listThree = ["seven", "eight", "nine"]
listOfLists = [listOne, listTwo, listThree]
print(listOfLists)
[['one', 'two', 'three'], ['four', 'five', 'six'], ['seven', 'eight', 'nine']]
Using a loop
The above code does work but is limited, especially if the number of elements of the list are not know until runtime.
A more useful way of creating lists within lists is to use a loop. We used the enumerate
function on the addresses
list so that we would have the current index numbers for the list elements as we loop over them. Notice the two
different methods we are using to accessing list items. In the addresses list we are getting the address component
from the range output. Furthermore, in order to line up the lists we also use the enumerate function to provide us
with the current list indices in the loop.
addresses = ["123 main", "456 main", "789 main"]
bedrooms = [5, 2, 1]
bathrooms = [3, 2, 1]
houses = []
for i, address in enumerate(addresses):
houses.append([address, bedrooms[i], bathrooms[i]])
print(houses)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
Using zip
In the code below we show how to use the zip function with a python list to quickly produce a list of tuples. Zip is nice because it will take the lists you give it and zip them together until it gets to the last item of the smallest list. If that is not what you want check out the next example where we use list comprehension to do even more list manipulation
addresses = ["123 main", "456 main", "789 main"]
bedrooms = [5, 2, 1]
bathrooms = [3, 2, 1]
houses = list(zip(addresses, bedrooms, bathrooms))
print(houses)
[('123 main', 5, 3), ('456 main', 2, 2), ('789 main', 1, 1)]
Using list comprehension
In the previous example we showed how to create a list of tuples, in the following code we will show how to modify that list of tuples to create a list of lists. List comprehensions in Python are a nice feature of the language and is a more concise way to modify a list. However, you should try not to put too much logic in a list comprehension otherwise it becomes hard to read. This is important because the version of yourself that has to come back in a few months to debug the code will thank you for being more explicit…or future you may let out a sigh of frustration when trying to remember what that list comprehension is doing
addresses = ["123 main", "456 main", "789 main"]
bedrooms = [5, 2, 1]
bathrooms = [3, 2, 1]
houses = list(zip(addresses, bedrooms, bathrooms))
houses = [[i, j, k] for i, j, k in houses]
print(houses)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
Converting to a Numpy multidimensional array
Numpy is a great package in Python and is used a lot by data scientist and machine learning engineers. One of the reasons is because of all the built-in linear algebra functionally that Numpy has packed into it. The linear algebra functions are very helpful as many of the algorithms used in ML and data science require this type of math.
import numpy as np
data1 = [1, 2, 3]
data2 = [5, 2, 1]
data3 = [3, 2, 1]
listOfList = [data1, data2, data3]
numpyArray = np.array(listOfList)
print(numpyArray)
[[1 2 3]
[5 2 1]
[3 2 1]]
Converting from a Numpy array
The toList method in Numpy will convert directly to a python list of lists while keeping the order of the inner lists intact. No need to create a new empty list and load it up with all the individual items. The toList method does all the heavy lifting for you.
import numpy as np
npArray = np.array([
[1, 2, 3],
[5, 2, 1],
[3, 2, 1]])
listOfLists = npArray.tolist()
print(listOfLists)
[[1, 2, 3], [5, 2, 1], [3, 2, 1]]
Converting to a Pandas Data Frame
Pandas Data frames are very powerful and incredibly useful for machine learning and data science tasks. Data frames can take in different types of data and group them all together and perform a tun of different built-in operations to make large data sets easy to work with. To get a better understanding of how data frames work the following example shows how to convert a lists of lists into a data frame
import pandas as pd
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1], ['321 park', 5, 3], ['432 park', 2, 2], ['543 park', 1, 1]]
df = pd.DataFrame(houses, columns=["address", "bedrooms", "bathrooms"])
print(df)
address bedrooms bathrooms
0 123 main 5 3
1 456 main 2 2
2 789 main 1 1
3 321 park 5 3
4 432 park 2 2
5 543 park 1 1
Converting from a Pandas Data Frame
Another one of the different approaches is to go from a pandas dataframe directly to a list vai pandas built in tolist()
method
import pandas as pd
df = pd.DataFrame([['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]], columns=["address", "bedrooms", "bathrooms"])
housesList = df.values.tolist()
print(housesList)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
Converting to a Dictionary
Another use case to is to convert a multidimensional list into a dictionary. To do this we will need to define a new value for the dict keys to story the different lists values in. In below example we will be using the address as the top dictionary key and the name of each value as the individual element keys
import pandas as pd
houses = [["123 main", 5, 3], ["456 main", 2, 2], ["789 main", 1, 1]]
housesDict = {}
for house in houses:
housesDict[house[0]] = {"address": house[0], "bedrooms": house[1], "bathrooms": house[2]}
print(housesDict)
{'123 main': {'address': '123 main', 'bedrooms': 5, 'bathrooms': 3}, '456 main': {'address': '456 main', 'bedrooms': 2, 'bathrooms': 2}, '789 main': {'address': '789 main', 'bedrooms': 1, 'bathrooms': 1}}
Converting from a Dictionary
Just like when converting a list to a dictionary we needed to add in the keys. The opposite is true when going from a dictionary to a list of lists. We can get just the values of a dictionary by calling the values() method on the dictionary object
housesDict = {'123 main': {'address': '123 main', 'bedrooms': 5, 'bathrooms': 3}, '456 main': {'address': '456 main', 'bedrooms': 2, 'bathrooms': 2}, '789 main': {'address': '789 main', 'bedrooms': 1, 'bathrooms': 1}}
housesList = []
for house in housesDict.values():
housesList.append(list(house.values()))
print(housesList)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
Converting to a Tuples
This can be done pretty compactly using tuple comprehension
housesList = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
housesTuple = tuple(tuple(item for item in house) for house in housesList)
print(housesTuple)
(('123 main', 5, 3), ('456 main', 2, 2), ('789 main', 1, 1))
Converting from a Tuples
This too can be done pretty compactly using list comprehension
housesTuple = (('123 main', 5, 3), ('456 main', 2, 2), ('789 main', 1, 1))
housesList = list(list(item for item in house) for house in housesTuple)
print(housesList)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
How to prepend to a List of Lists
Here we are going to add a new object to the first element of the original list
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
moreHouses = [['321 park', 5, 3], ['654 park', 2, 2], ['987 park', 1, 1]]
for house in moreHouses:
houses.insert(0, house)
print(houses)
[['987 park', 1, 1], ['654 park', 2, 2], ['321 park', 5, 3], ['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
How to append to a List of Lists
In the below code snippet we are going to add a new element to the end of the list
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
anotherHouse = ['900 main', 5, 3]
houses.append(anotherHouse)
print(houses)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1], ['900 main', 5, 3]]
How to insert into the middle of a List of Lists
Here we are adding a new object in the middle of a list by specifying the list index to insert into
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
anotherHouse = ['400 main', 5, 3]
houses.insert(1, anotherHouse)
print(houses)
[['123 main', 5, 3], ['400 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
Concatenate two multidimensional list together
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
moreHouses = [['321 park', 5, 3], ['654 park', 2, 2], ['987 park', 1, 1]]
for house in moreHouses:
houses.append(house)
print(houses)
[['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1], ['321 park', 5, 3], ['654 park', 2, 2], ['987 park', 1, 1]]
Remove last element
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
houses.pop()
print(houses)
[['123 main', 5, 3], ['456 main', 2, 2]]
Remove the first item
houses = [['123 main', 5, 3], ['456 main', 2, 2], ['789 main', 1, 1]]
houses.pop(0)
print(houses)
[['456 main', 2, 2], ['789 main', 1, 1]]
Converting to a flat list
There are several ways to convert a whole list of lists into a flat list. If you are dealing with numbers than the easiest way is to use a Numpy array
import numpy as np
data1 = [1, 2, 3]
data2 = [5, 2, 1]
data3 = [3, 2, 1]
listOfList = [data1, data2, data3]
numpyArray = np.array(listOfList)
flatList = list(numpyArray.flat)
print(flatList)
[1, 2, 3, 5, 2, 1, 3, 2, 1]