Movatterモバイル変換


[0]ホーム

URL:


Open In App

Given an array of integers, find the sum of its elements. For Examples:

Input: [1, 2, 3]
Output: 6
Explanation: 1 + 2 + 3 = 6

Let's explore different methods to find the sum of an array one by one:

Using sum() Function

Python provides a built-insum() function to calculate the sum of elements in a list, tuple or set.

Python
arr=[12,3,4,15]ans=sum(arr)print('Sum:',ans)

Output
Sum: 34

Using reduce() Method

Thereduce() function from functools applies a function cumulatively to the elements of an iterable, effectively summing all elements.

Python
fromfunctoolsimportreducearr=[12,3,4,15]ans=reduce(lambdaa,b:a+b,arr)print('Sum:',ans)

Output
Sum: 34

Explanation: reduce() applies a function cumulatively to items of the iterable, combining them into a single result (here it repeatedly adds pairs).

Using Iteration

Iterating through the array and adding each element to the sum variable and finally displaying the sum.

Python
arr=[12,3,4,15]t=0forxinarr:t+=xprint('Sum:',t)

Output
Sum: 34

Using enumerate() Function

enumerate() allows looping through an array with an index and element. This method adds each element to a running sum.

Python
arr=[12,3,4,15]t=0fori,valinenumerate(arr):t+=valprint(t)

Output
34

Explanation: for i, val in enumerate(arr) loop over arr while also receiving the index i (0, 1, 2, ...) and the element val.

Please refer complete article onProgram to find sum of elements in a given array for more details!


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp