Constructing a list of lists in Python is relatively straightforward, as one main list is composed of the other. Sublists (inner lists) containing elements/items enclosed in a main outer list. However, the list is one of the most important data structures in Python. Lists in python are quite flexible data structures. You can append, insert, clear and remove an item easily if you want to modify the list. However, a List is a sequence of elements that can be any Python object. Let’s see how to construct a list of lists!
There are various ways to construct a list of lists depending on the type of elements being used. The approaches discussed on this page are:
- Using the append() function to create a list of lists in Python
- Using the list initializer to construct a list of lists in Python
- Using list comprehension to create a list of lists in Python
- Using non-list comprehension to build a list of lists in Python
- Using Nested List Comprehension to create a list of lists in Python
- Using the Numpy module to construct a list of lists in Python
- Using Nested For Loop in aggregation with append() method of Python to create a list of lists in Python
- Using the split() function of Python to construct a list of lists in Python
- Using the map() function to create a list of lists in Python
Working on Jupyter Notebook Anaconda Environment Python version 3.0+
List of lists in Python: What does it mean?
Using lists to store multiple elements or items in a single variable is standard practice. The term nested list refers to any list with another list (list of lists) containing an item/element (sublist). The items or elements of a list in Python are separated by commas (,) and enclosed in square brackets[]. The syntax to construct a list of lists in Python follows:
list_of_lists=[1,2,['Python'] ]
print(list_of_lists)
type(list_of_lists)
[1, 2, ['Python']]
list
Where,
1,2,[‘Python’] are sublists enclosed within a main list forming a list of lists.
Using the append() function to create a list of lists in Python
Using the append() function to create a list of lists in Python, a list of lists can be constructed using Python’s append method. However, as noted here, the new list will be added or appended at the end of the main list. Moreover, the following example uses the append() function to accomplish its task:
- Create a list with two sublists, one for each side.
- Use the append method to add another element to each sublist.
- This will add another element to the end of the second sublist, creating a new list containing elements.
- Noted! The variable must be stored in a list before you can construct a list of lists. Append the newly created lists to a new empty list. A list of lists will result upon execution.
# Create lists
list_1 = ['1','2','3']
input_list = input('append list by: ')
# Create an empty list
list = []
# Create List of lists
list.append(list_1)
list.append(input_list)
print (list)
append list by: 4
[['1', '2', '3'], '4']
An example to storing the flower data:
data_1= ['sepal','patels','leaves','stems','roots','fruit']
data_2= ['leaves', 'roots']
list_1=data_1
list_2=data_2
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)
listoflists
[['sepal', 'patels', 'leaves', 'stems', 'roots', 'fruit'], ['leaves', 'roots']]
Using the list initializer to construct a list of lists in Python
Taking lists as elements with a list initializer. Constructing a list of lists by passing sublists as items/elements. Hence, in this way, we can create a list of lists.
# construct two lists
data_1, data_2= ['sepal','patels','leaves','stems','roots','fruit'], ['leaves', 'roots']
# construct the List of lists
list = [data_1, data_2]
# Display list of lists
print(list)
[['sepal', 'patels', 'leaves', 'stems', 'roots', 'fruit'], ['leaves', 'roots']]
Using list comprehension to create a list of lists in Python
List comprehension is a one-liner, more Pythonic approach for constructing a list of lists in Python.
Here is an example to better understand constructing a list of lists in Python using the list comprehension approach.
# construct a lists
data_1= ['sepal','patels','stems']
# construct the List of lists using list comprehension
list = [data_1 for i in range(1)]
print(list)
[['sepal', 'patels', 'stems']]
Using non-list comprehension to construct a list of lists in Python
Non-list comprehension performs a similar task to a list comprehension, but non-list comprehension is not a one-liner command to execute the program. However, It has more than one line command to run the program.
# Create an list
listoflists = ['sepal','patels','stems']
# Iterate over a range of 1
for i in range(1):
# while iteration, add an new list containing element to the main list
listoflists.append(['leaves'])
print('List of lists:', listoflists)
List of lists: ['sepal', 'patels', 'stems', ['leaves']]
To checklist has different and unique elements, use the elem function in aggregation with the id function in Python.
# Create an list of flowers parts
listoflists = ['sepal','patels','stems']
# Iterate over a range of 1
for i in range(1):
# while iteration, add an new list containing element to the main list
listoflists.append(['leaves'])
print('List of lists:', listoflists)
for elem in listoflists:
print(id(elem))
List of lists: ['sepal', 'patels', 'stems', ['leaves']]
1810016235248
1810016231856
1810016234032
1810016289088
All four sublists have unique objects, so they return different IDs.
Using Nested List Comprehension to create a list of lists in Python
Creating each inner list and creating the output list from the inner lists can be done using a list comprehension expression (using for…in structure within square brackets []). Using this method, unique inner list objects are created and then combined, pythonically, into the outer list.
To create a 2D list of lists, do the following procedure:
- Iterating through the list until variable i goes from 0 to 2 is the result of executing for i in range(3) structure.
- To append its output to the list, invoke list comprehension for..in structure in the code. The list comprehension structure appends the result until the total iteration is completed.
- However, the final nest list consists of repeating iterations up to 3 times.
listoflists = [[j for j in range(3)] for _ in range(3)]
print(listoflists)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Another way to do the similar task is to print an exponentially growing star patterns using a construct list of lists:
List comprehension is a pretty accurate way to print the n-dimensional nested list in Python.
lists = [['*'*j for j in range(i)] for (i) in range(6)]
lists
[[],
[''],
['', '*'],
['', '*', '**'],
['', '*', '**', '***'],
['', '*', '**', '***', '****']]
Using the Numpy module to construct a list of lists in Python
An empty Numpy array can be constructed with the built-in empty() function in the Numpy module in Python, which returns the nested array of provided shape. However, using NumPy to display or handle numerical values. Moreover, To construct a 2-dimensional Numpy array, you need to convert it into a list data type using the built-in List command or use tolist() function.
np.empty()
np.empty() creates an array based on the specified shape tuple. The syntax is:
np.empty((inner list, outer list))
empty() function
Noted that:
Unlike ‘ZEROS,’ ‘empty’ avoids setting array values to zero, which may result in marginal performance benefits. It, however, requires users to set all array values manually.
Here’s an example with two inner lists, each with two elements constructing a list of lists:
#importing numpy as np
import numpy as np
# constructing a 2D Numpy array of shape two inner list (sublist) and one outer (main list) (2, 1)
#empty_like : Return an empty array with shape and type of input.
list_of_lists_empty = np.empty((2, 1))
#zeros : Return a new array setting values to zero.
list_of_lists_zeros = np.zeros((2, 1))
#ones : Return a new array setting values to one.
list_of_lists_ones = np.ones((2, 1))
#full : Return a new array of provides shape filled with value.
list_of_lists_full = np.full((2, 1), '*', dtype=None )
print('List of lists:')
print(list(list_of_lists_empty))
print(list(list_of_lists_zeros))
print(list(list_of_lists_ones))
print(list(list_of_lists_full))
List of lists:
[array([1.]), array([1.])]
[array([0.]), array([0.])]
[array([1.]), array([1.])]
[array(['*'], dtype='<U1'), array(['*'], dtype='<U1')]
Using Nested For Loop in aggregation with append() method of Python to create a list of lists in Python
To add an element to the inner list and an inner list to the outer list, use the append() method. Here using for..in structure(non-list comprehensive) approach coupled with append to construct a list of lists to draw a 2D star pattern (*) in Python more straightforwardly and comprehensively.
Here is how it executes:
list_of_lists= []
for i in range(4):
sublist = []
for j in range(3):
sublist.append('*'*j)
list_of_lists.append(sublist)
list_of_lists
[['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**'],
['', '*', '**']]
Using the split() function of Python to construct a list of lists in Python
First, extract each element from the list in the list format itself, append it, and store it to an empty list [] using Python’s split() function during alteration. However, it returns a list with new appended attributes defined in the scope. However, this can be achieved by calling a function after computation.
def characters(lst):
empty_list = []
for i in lst:
sublist = i.split()
empty_list.append(sublist)
return(empty_list)
listoflists = ['*', '@', '%']
print(characters(listoflists))
[['*'], ['@'], ['%']]
Using the map() function to create a list of lists in Python
The following example maps the function i:[i] for each item of the provided iterable ‘listoflists.’ However, after the execution map returns, each element of a function attribute becomes an inner list using the i:[i] format. Hence creating a list of lists.
def num(listoflists):
return list(map(lambda i:[i], listoflists))
listoflists = ['*', '**', '***']
print(num(listoflists))
[['*'], ['**'], ['***']]
Conclusion
This article demonstrates different ways, with examples of code, to construct a list of lists in Python. A list of lists is computationally similar to a nested list. However, there are specific cautions for creating a list of lists for integers or strings or another data type.
If you want to learn more about Python Programming, visit Python Programming Tutorials.