The function takes a list and returns an int depending on how many lists are in the list not including the list itself. (For the sake of simplicity we can assume everything is either an integer or a list.)
For example:
x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
count_list(x) # would return 8
I think using recursion would help but I am not sure how to implement it, this is what I have so far.
def count_list(a,count=None, i=None):
if count==None and i==None:
count=0
i=0
if i>len(a)
return(count)
if a[i]==list
i+=1
count+=1
return(count_list(a[i][i],count))
else:
i+=1
return(count_list(a[i]))
A nested list, l , is taken with sub-lists. Count variable is used to count the number of even numbers in the list and is initialized to zero. The nested for loop is used to access the elements in the list. Variable i is used to access sub-lists in the list, and variable j is used to access elements in sub-list i .
To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function.
Use list. __len__() to count elements in a list. We can directly call the __len__() member function of list to get the size of list i.e.
You can use a recursion function as following:
In [14]: def count(l):
...: return sum(1 + count(i) for i in l if isinstance(i,list))
...:
In [15]:
In [15]: x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]
In [16]: count(x)
Out[16]: 8
This seems to do the job:
def count_list(l):
count = 0
for e in l:
if isinstance(e, list):
count = count + 1 + count_list(e)
return count
Here is a non-recursive solution:
The code:
def count_list(lst):
""" Given a master list, count the number of sub-lists """
stack = lst[:]
count = 0
while stack:
item = stack.pop()
if isinstance(item, list):
# If the item is a list, count it, and push back into the
# stack so we can process it later
count += 1
stack.extend(item)
return count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With