w3resource

Python Data Structures and Algorithms - Recursion: Sum of a list of numbers

Python Recursion: Exercise-1 with Solution

Write a Python program to calculate the sum of a list of numbers using recursion.

Sample Solution:

Python Code:

# Define a function named list_sum that takes a list of numbers as input
def list_sum(num_List):
    # Check if the length of the input list is 1
    if len(num_List) == 1:
        # If the list has only one element, return that element
        return num_List[0]
    else:
        # If the list has more than one element, return the sum of the first element
        # and the result of recursively calling the list_sum function on the rest of the list
        return num_List[0] + list_sum(num_List[1:])

# Print the result of calling the list_sum function with the input [2, 4, 5, 6, 7]
print(list_sum([2, 4, 5, 6, 7]))

Sample Output:

24

Flowchart:

Flowchart: Recursion: Sum of a list of numbers.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Python Recursion Exercise Home.
Next: Write a Python program to converting an integer to a string in any base.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/data-structures-and-algorithms/python-recursion-exercise-1.php