In this example we are going to see how we can iterate a list recursively with Python. And the lists of Python can also contain other lists, therefore we must have a way to go through the main list and go through, in turn, the nested lists. Regardless of the degree of nesting we have.
The first thing will be to define the list in Python.
list = [1,2,3,['a','b','c','d'],4,5]
As we can see, the fourth element is in turn a list. Remember that the elements of the lists in Python are defined by square brackets and separated by commas.
To be able to scroll through the list at Python we use a for-each loop as follows:
for n in list:
print n
In order to reuse the code we are going to define a method which will create the code that runs through the list.
def list (list):
for n in list:
print n
When we execute this code the result we have is the following:
1
2
3
[‘a’, ‘b’, ‘c’, ‘d’]
4
5
We see that the list that occupied the fourth element is printed as is. So we will have to modify the code to ask if the element is a list. For them we use the isinstance() method to which we pass the element.
What we are going to do is that in the event that the element is a list, call the list() method again, which will cause the code that iterates through the elements of the list to be executed again, but will not allow a list to be iterated recursively with Python.
def list (list):
for n in list:
if isinstance(n,list):
list(n)
else:
print n
The result we get now is:
1
2
3
a
b
c
d
4
5
This way we already have the code we were looking for and that helps us iterate a list recursively with Python.
