Can you nest lists in python?


A nested list is a list within a list. Python provides features to handle nested list gracefully and apply common functions to manipulate the nested lists. In this article we will see how to use list comprehension to create and use nested lists in python.

Creating a Matrix

Creating a matrix involves creating series of rows and columns. We can use for loop for creating the matrix rows and columns by putting one python list with for loop inside another python list with for loop.

Example

 Live Demo

matrix = [[m for m in range(4)] for n in range(3)]
print(matrix)

Running the above code gives us the following result:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

Filtering from Nested List

We can use the list comprehension with filtering feature by using the for loop within the sub-lists. Below we have a 2 dimensional list with one layer of sub-list inside a bigger list. We access selective elements from each of these nested lists. By using a filter condition.

Example

 Live Demo

years = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August', 'September'],['October','November','December']]
# Nested List comprehension with an if condition
years = [years for sublist in years for years in sublist if len(years) <= 5]
print(years)

Running the above code gives us the following result:

['March', 'April', 'May', 'June', 'July']

Flattening nested Sub-Lists

We can also take a nested list and flatten it by creating a single list without having any sub-list inside it.

Example

 Live Demo

nested_list = [[1] ,[17, 19], [21,23,25], [32,35,37,39]]
# Nested List Comprehension to flatten a given 2-D matrix
flattened_list = [value for sublist in nested_list for value in sublist]
print(flattened_list)

Running the above code gives us the following result:

[1, 17, 19, 21, 23, 25, 32, 35, 37, 39]

Can you nest lists in python?

Updated on 30-Dec-2019 10:32:32

  • Related Questions & Answers
  • Python List Comprehension?
  • Python List Comprehension and Slicing?
  • Count set bits using Python List comprehension
  • Python Dictionary Comprehension
  • How to catch a python exception in a list comprehension?
  • How to create a dictionary with list comprehension in Python?
  • Python - Convert given list into nested list
  • Flatten Nested List Iterator in Python
  • How will you explain Python for-loop to list comprehension?
  • Python - Convert List to custom overlapping nested list
  • Nested List Weight Sum II in Python
  • Convert a nested list into a flat list in Python
  • Python program to Flatten Nested List to Tuple List
  • List comprehension and ord() in Python to remove all characters other than alphabets
  • K’th Non-repeating Character in Python using List Comprehension and OrderedDict

Reverse, flatten, convert to a dictionary, and more

Can you nest lists in python?
Photo by Magda Ehlers from Pexels

Python List is one of the most important data structures. Python list can contain sub-list within itself too. That’s called a nested list.

While working with the python nested list, I came across some scenarios. I have shared those in this article. Like how to access the element, replace an element, count the occurrences of an element in the nested list, etc.


1. How to check if an element is present in a nested list?

Using any() function

any(elem in sub_list for sub_list in nested_list)
  • If element present in the nested list returns True else returns False.
n1=[['red','orange','yellow'],['apple','banana'],['carrot']]

#to check whether the element present in the nested list
print(any('apple' in inner_list for inner_list in n1))
#Output: True

print(any('strawberry' in inner_list for inner_list in n1))
#Output:False

2. How to reverse the nested list?

Using indexing

If we want to reverse the elements (sub_list) in the nested list, we can use the indexing method.

my_list[::-1] — It will reverse the elements in the nested list. It will create a copy of the nested list. It won’t modify the original list.

my_list=[[1,2],[3,4],[5,6,7]]
result=my_list[::-1]
print(result)
#Output:[[5, 6, 7], [3, 4], [1, 2]]

Using reverse()

my_list.reverse()reverse() function also reverse the elements in the nested list and modify the original list itself.

my_list=[[1,2],[3,4],[5,6,7]]
my_list.reverse()
print(my_list)
#Output:[[5, 6, 7], [3, 4], [1, 2]]

How to reverse the elements in the sub-list?

Suppose, if we want to reverse the elements in the sub_list, then we have to iterate through the sub_list in the nested_list and apply the reverse function to that sub_list.

my_list=[[1,2],[3,4],[5,6,7]]
for sub_list in my_list:
sub_list.reverse()
print(my_list)
#Output: [[2, 1], [4, 3], [7, 6, 5]]

3. How to flatten a nested list?

By using list comprehension, we can flatten the nested list. This is one way of doing it.

[element for element in sub_list for sub_list in nested_list]
  • First, iterate through the nested list, then iterate through the sub_list and get each element.
my_list=[[1,2],[4,5,6],[7,8]]
result=[v1 for sub_list in my_list for v1 in sub_list]
print(result)
#Output:[1, 2, 4, 5, 6, 7, 8]

4. Find the index of all occurrences of an item in a Python nested list?

Using index() method

First, iterate through the sublist in the nested list, then check if that particular element exists in that sub_list. If it exists, find the index of the sub_list and the index of the element in that sub_list.

my_list=[['red','orange'],['apple','banana','orange'],['carrot']]
for sub_list in my_list:
if 'orange' in sub_list:
print((my_list.index(sub_list),sub_list.index('orange')))

'''
#Output:
(0, 1)
(1, 2)
'''

#Checking whether the index of that element "orange" is correct
print(my_list[0][1])
print(my_list[1][2])

Using List Comprehension

[(index1,index2) for (index1,sub_list) in enumerate(nested_list) 
for (index2,element) in enumerate(sub_list) if element==’X’]
  • It will return a list of tuples containing index of that particular element.
for (index1,sub_list) in enumerate(nested_list)

enumerate function will iterate over the iterable and returns the index and values obtained by iterating over iterable.

my_list=[['red','orange'],['apple','banana','orange'],['carrot']]
result=[(i1,i2) for (i1,v1) in enumerate(my_list) for (i2,v2) in enumerate(v1) if v2=='orange']
print(result)

#Output:
[(0, 1), (1, 2)]

https://gist.github.com/IndhumathyChelliah/eb0a7a2785da4fe7ddcc1ce434c970e05. How to count the occurrences of an element in the nested list?

In the list, we can find the count of occurrences of an element using the count() method.

l1.count()

In nested_list, we iterate through the sub_list, then find the count of that particular element in each sub_list and then add the count using the sum() function.

my_list=[[9,4],[1,8,4],[3,2]]
result=sum(sub_list.count(4) for sub_list in my_list)
print(result)
#Output: 2

6. How to remove an element from the nested list?

Using remove() method

First, iterate through the nested _list and then iterate through the elements in the sub_list and check if that particular element exists. If yes means, remove that element using the remove() method.

It will remove all occurrences of that particular element from the nested list.

my_list=[[1,2,3],[3,4,5]]
for sub_list in my_list:
for elem in sub_list:
if elem==3:
sub_list.remove(3)
print(my_list)
#Output: [[1, 2], [4, 5]]

Using List Comprehension

Iterate through the nested list and then iterate through the sub_list and retain only the elements which don’t match the element to be removed.

my_list=[[1,2,3],[3,4,5]]
result=[[elem for elem in sub_list if elem!=3]for sub_list in my_list]
print(result)
#Output: [[1, 2], [4, 5]]

7. How to insert elements at a particular index in the nested list?

If we want to insert an element at a particular index, we can do that by using the insert() method.

Iterate through the sub_list in the nested_list, if the index of the sub_list matches, insert the element using:

sub_list.insert(index,element_to_inserted)
my_list=[[1,2],[4,5]]
for ind,sub_list in enumerate(my_list):
if ind==1:
sub_list.insert(0,3)

print(my_list)
#Output: [[1, 2], [3, 4, 5]]

8. How to replace all occurrences of an element in a nested list?

Get the index of the element which needs to be replaced and then assign the new element by mentioning the index:

my_list[index1][index2]=’X’

We can get the index of the sub_list and the index of that particular element from the sub_list using enumerate() function.

my_list=[[1, 2], [3,4], [3, 5], [6]]

for i1,sub_list in enumerate(my_list):
for i2,elem in enumerate(sub_list):
if elem==3:
my_list[i1][i2]=33

print(my_list)
#Output: [[1, 2], [33, 4], [33, 5], [6]]

9. How to convert a nested list into a dictionary?

Example 1

In the given nested list example, the first element in each sub_list is a key and the second element is the corresponding value.

First, we can iterate through the nested list and then assign the first element as a key and the second element as a value.

d[key]=value 
d[sub_list[0]]=sub_list[1]
my_list=[['fruit','apple'],['color','red'],['animal','dog']]

result={}
for sub_list in my_list:
result[sub_list[0]]=sub_list[1]

print(result)
#Output: {'fruit': 'apple', 'color': 'red', 'animal': 'dog'}

Example 2

In the given nested list example, the first element in each sub_list is a key and the remaining elements are the corresponding value.

d[sub_list[0]]=sub_list[1:]

sub_list[1:] — It will take all elements from the first index.

my_list=[['fruit','apple','banana','grapes'],['color','red','blue'],['animal','dog']]

result={}
for sub_list in my_list:
result[sub_list[0]]=sub_list[1:]

print(result)
#Output: {'fruit': ['apple', 'banana', 'grapes'], 'color': ['red', 'blue'], 'animal': ['dog']}

10. How to convert a nested list into a Pandas dataframe?

Example 1

In the below example, the first sub_list contains column_names, remaining sub_list contains the corresponding values.

my_list=[['Fruits','Price'],['apple','10

Output:

Can you nest lists in python?

Example 2

In the below example, all the sub_list contains the values. No column names in the sub_list.

my_list=[['Grapes','15

Output:

Can you nest lists in python?

Conclusion

In this article, I have covered some important tips on how to use nested lists in Python. Compared to regular Python lists, operations on nested lists are to be performed a little differently.

I hope you all liked it. Thanks for reading.

Buy me a Coffee

How do I make a nest list in Python?

Python Nested Lists First, we'll create a nested list by putting an empty list inside of another list. Then, we'll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.

How do you nest two lists in Python?

How to Create a List of Lists or Nested List in Python?.
# Take two lists list1 = [1,2,3,4] list2 = [5,6,7,8] list3 = [] # Take an empty list # make list of lists list3. ... .
# Take two lists list1 = [1,2,3,4] list2 = [5,6,7,8] # make list of lists list3 = [list1, list2] # Display result print(list3).

How do I make a nesting list?

The proper way to make HTML nested list is with the nested
    as a child of the
  • to which it belongs. The nested list should be inside of the
  • element of the list in which it is nested.

How do I arrange a nested list in Python?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.