I'm finally getting around to recursion in Python and trying to count the number of occurrences of a target number in a list
. However, I'm running into issues with counting occurrences in a nested list
of numbers.
For example
def count(lst, target):
if lst == []:
return 0
if lst[0] == target:
return 1 + count(lst[1:], target)
else:
return 0 + count(lst[1:], target)
Output
>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )
Output: 1
Expected output: 2
Is there an easy way to flatten nested-lists in Python? Or a simple way for me to account for the fact that there is a nested-list in my code?