0

Is this the best way to count the amount of elements recursively?

Is this the best way to count the amount of elements recursively? def foo(l): if not l: return 0 del l[0] return foo(l) + 1 a = [1, 2, 3] print(foo(a))

4th Oct 2021, 5:19 AM
Yahel
Yahel - avatar
5 ответов
+ 1
It is, but you can't use the list a after calling foo
4th Oct 2021, 5:43 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
Answer from Stack Overflow b = ['d'] c = ['e', 'f'] h = [] a = [b,c,h] def recur(l,call=1): if not l: return 0 else: print("l = {} and l[0] = {} on recursive call {}".format(l,l[0],call)) call+=1 return recur(l[1:],call) + len(l[0])
4th Oct 2021, 5:48 AM
Deyzze
Deyzze - avatar
+ 1
I can't say if it's the best one, but it's simple. after calling method foo the list will be empty, which means refilling the list.
4th Oct 2021, 6:06 AM
Erlénio.RS
Erlénio.RS - avatar
0
Well, I made this: def foo(l,num=0): try: l[num] return foo(l,num+1) except: return num a = [1,2,3] print(foo(a)) print(a)
4th Oct 2021, 6:32 AM
Eashan Morajkar
Eashan Morajkar - avatar
0
The list will also be available
4th Oct 2021, 6:32 AM
Eashan Morajkar
Eashan Morajkar - avatar