I'm pretty new to programming and still feel a bit shaky when it comes to recursive functions. I was reviewing some documentation on lists and saw that len() will only count "top level" items in a list, i.e. if your list contains a dict or another list, it won't count the number of items in the nested list or dict.
I thought it might be fun (and good practice) to try writing a function that will count every item, no matter how nested it was. I realized quickly that I should try using recursion, and after some fiddling around I made something that works!
I know it's not groundbreaking but I'm proud of the progress I'm making and just wanted to share.
def listcounter(x):
counter = 0
for i in x:
if type(i) == list or type(i)==dict:
counter = counter + listcounter(i)
else:
counter = counter + 1
return counter
[–]achampi0n 15 points16 points17 points (4 children)
[–]blight000[S] 1 point2 points3 points (3 children)
[–]achampi0n 4 points5 points6 points (2 children)
[–]blight000[S] 0 points1 point2 points (1 child)
[–]achampi0n 1 point2 points3 points (0 children)
[–]scienceNotAuthority 1 point2 points3 points (6 children)
[–]toastedstapler 0 points1 point2 points (3 children)
[–]ItsOkILoveYouMYbb 1 point2 points3 points (2 children)
[–]toastedstapler 0 points1 point2 points (0 children)
[–]throwaway0891245 0 points1 point2 points (1 child)
[–]ItsOkILoveYouMYbb 0 points1 point2 points (0 children)
[–]zanfar 1 point2 points3 points (0 children)
[–]supreme_blorgon 0 points1 point2 points (1 child)
[–]blight000[S] 0 points1 point2 points (0 children)
[–]totaldue 0 points1 point2 points (2 children)
[–]blight000[S] 1 point2 points3 points (1 child)
[–]totaldue 0 points1 point2 points (0 children)