10 Important Tips for Using Nested Lists in Python

Reverse, flatten, convert to a dictionary, and more

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:

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:


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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s