Python Nested List Explained With Examples
How to Create a Nested List in Python?
A nested list is made up of a series of sublists separated by commas.
Example:
L = ['a', ['b', ['c', 'd'], 'e', 'f'], 'g', 'h']
How to Access Nested List Items by Index?
The following are the indices for the entries in a nested list:
List1 = ['a', 'b', ['c', 'd', ['e', 'f']], 'g', 'h']
print(List1[2])
Output:
Output:
Output:
Negative List Indexing In a Nested List
Negative indexing can also be used to reach a nested list.
Negative indexes work backwards from the list's end. As a result, L[-1] denotes the final item, L[-2] the second-to-last, and so on.
The negative indices for the elements in a nested list are shown in the following example:
List1 = ['a', 'b', ['c', 'd', ['e', 'f']], 'g', 'h']
print(List1[-3])
Output:
Output:
Output:
How to Change Nested List Item Value in Python?
By referring to the index number of a specific item in a hierarchical list, you may modify its value.
List1 = ['a', ['b', 'c'], 'd']
List1[1][1] = 0
print(List1)
Output:
How to Add items to a Nested List in Python?
Use the append() method to add additional values to the end of the nested list.
List1= ['a', ['b', 'c'], 'd']
List1[1].append('x')
print(List1)
Output:
Use insert() method to add an element at a given place in a nested list.
List1= ['a', ['b', 'c'], 'd']
List1[1].insert(0,'x')
print(List1)
Output:
Using the extend() method, you can combine two lists into one.
List1 = ['a', ['b', 'c'], 'd']
List1[1].extend([1,2,3])
print(List1)
Output:
How to Remove items from a Nested List in Python?
The pop()
method can be used if you know the index of the object you desire. It changes the list and replaces the item that was removed.
List1 = ['a', ['b', 'c', 'd'], 'e']
x = List1[1].pop(1)
print(List1)
print(x)
You can use the del function in case there is no need for the removed value.
List1 = ['a', ['b', 'c', 'd'], 'e']
del List1[1][1]
print(List1)
In case you aren't sure about the location of an item in the list, you can use the remove() function to delete it by value.
List1 = ['a', ['b', 'c', 'd'], 'e']
List1[1].remove('c')
print(List1)
How to Find Nested List Length in Python?
The built-in len() method may be used to determine the number of items in a nested sublist.
List1= ['a', ['b', 'c'], 'd']
print(len(List1))
Output:
print(len(List1[1]))
Output:
How to Iterate through a Nested List?
Use the basic for loop to traverse over the entries in a nested list.
List1 = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
for list1 in List1:
for number in list1:
print(number, end=' ')
Output: