Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert for loop to recursive function in python3

Is it possible to convert the following loop:

c = 0
for a in find:
    c += 1
return c

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

like image 411
J0ker98 Avatar asked Apr 23 '26 08:04

J0ker98


1 Answers

def count(ls):
    if not ls:  # empty
        return 0
    return count(ls[1:]) + 1

Use it like this:

>>> find = [a, b, c, d]
>>> count(find)
4
like image 97
L3viathan Avatar answered Apr 24 '26 21:04

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!