Skip to content

Instantly share code, notes, and snippets.

@ishahid
Created January 15, 2014 02:39
Show Gist options
  • Save ishahid/8429857 to your computer and use it in GitHub Desktop.
Save ishahid/8429857 to your computer and use it in GitHub Desktop.
Recursive sum of all elements of a given list.
def sum(args):
""" Returns sum of all elements of a given list, recursively """
if len(args) == 0:
return 0
return args[0] + sum(args[1:])
if __name__ == "__main__":
list1 = []
print 'sum of []:',
print sum(list1)
list2 = [1]
print 'sum of [1]:',
print sum(list2)
list3 = [1, 2, 3]
print 'sum of [1, 2, 3]:',
print sum(list3)
list4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print 'sum of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:',
print sum(list4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment