Sum of first n elements in list python

I am working on the following Python list exercise from codingbat.com:

Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. Examples:

sum2[[1, 2, 3]] → 3 

sum2[[1, 1]] → 2

sum2[[1, 1, 1, 1]] → 2

My solution below works:

def sum2[nums]:
  if len[nums]>=2:
    return nums[0] + nums[1]
  elif len[nums]==1:
    return nums[0]
  return 0

But I wonder if there's any way to solve the problem with fewer conditional statements.

jonrsharpe

110k25 gold badges216 silver badges397 bronze badges

asked Jul 18, 2014 at 13:59

2

There is. Two elements of the solution - builtin function sum and lists's slices:

>>> sum[[1,2,3][:2]]
3
>>> sum[[1,1,1,1][:2]]
2
>>> sum[[1,1][:2]]
2
>>> sum[[1][:2]]
1
>>> sum[[][:2]]
0

answered Jul 18, 2014 at 14:02

Roman BodnarchukRoman Bodnarchuk

28.5k12 gold badges58 silver badges73 bronze badges

5

If you can't use sum, one possible solution uses exceptions:

totalsum = 0
try:
  totalsum += nums[0]
  totalsum += nums[1]
except IndexError:
  pass
return totalsum

Catch the error and short-circuit the summation if an element doesn't exist. Easier to ask forgiveness than permission, as they say.

answered Jul 18, 2014 at 14:04

TheSoundDefenseTheSoundDefense

6,4481 gold badge28 silver badges41 bronze badges

4

try this:

def sum2[nums]:
  if len[nums] == 1:
    return nums[0]
  else:
    return sum[nums [:2]]

answered May 4, 2017 at 18:41

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a list of numbers, write a Python program to find the sum of all the elements in the list.

    Example:  

    Input: [12, 15, 3, 10]
    Output: 40
    Input: [17, 5, 3, 5]
    Output: 30

    Example #1: 

    Python3

    total = 0

    list1 = [11, 5, 17, 18, 23]

    for ele in range[0, len[list1]]:

        total = total + list1[ele]

    print["Sum of all elements in given list: ", total]

    Output

    Sum of all elements in given list:  74

    Example #2 : Using while[] loop  

    Python3

    total = 0

    ele = 0

    list1 = [11, 5, 17, 18, 23]

    while[ele < len[list1]]:

        total = total + list1[ele]

        ele += 1

    print["Sum of all elements in given list: ", total]

    Output: 
     

    Sum of all elements in given list:  74

    Example #3: Recursive way  

    Python3

    list1 = [11, 5, 17, 18, 23]

    def sumOfList[list, size]:

        if [size == 0]:

            return 0

        else:

            return list[size - 1] + sumOfList[list, size - 1]

    total = sumOfList[list1, len[list1]]

    print["Sum of all elements in given list: ", total]

    Output

    Sum of all elements in given list:  74

    Example #4: Using sum[] method  

    Python3

    list1 = [11, 5, 17, 18, 23]

    total = sum[list1]

    print["Sum of all elements in given list: ", total]

    Output: 

    Sum of all elements in given list:  74

    Example 5: Using add[] function of operator module

    First we have to import the operator module then using the add[] function of operator module adding the all values in the list. 

    Python3

    from operator import*

    list1 = [12, 15, 3, 10]

    result = 0

    for i in list1:

        result = add[i, 0]+result

    print[result]

    Method 6: Using enumerate function

    Python3

    list1 = [12, 15, 3, 10];s=0

    for i,a in enumerate[list1]:

      s+=a

    print[s]

    Method 7: Using list comprehension 

    Python3

    list1 = [12, 15, 3, 10]

    s=[i for i in list1]

    print[sum[s]]

    Method 8: Using lambda function

    Python3

    list1 = [12, 15, 3, 10]

    print[sum[list[filter[lambda x: [x],list1]]]]

    Method: Using add operator 

    Python3

    import operator

    list1 = [12, 15, 3, 10] ;s=0

    for i in list1:

      s=s+operator.add[0,i]

    print[s]


    How do you find the sum of the first n elements in a list Python?

    1 Answer.
    Use itertools.islice[] to efficiently extract those elements: from itertools import islice sum[islice[somelist, k]].
    Slice the list to get a copy with just those first elements: sum[somelist[:k]].

    How do you sum items in a list in Python?

    Python provides an inbuilt function sum[] which sums up the numbers in the list. Syntax: sum[iterable, start] iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

    How do you sum the first four elements of a list in Python?

    sum of first 4 elements in an array python.
    #Python program to add first 4 elements using the built-in function..
    lst = [].
    num = int[input["Enter the size of the array: "]].
    print["Enter array elements: "].
    for n in range[num]:.
    numbers = int[input[]].
    lst. append[numbers].
    print["Sum:", sum[lst[:4]]].

    How do you sum elements in a list?

    Sum Of Elements In A List Using The sum[] Function. Python also provides us with an inbuilt sum[] function to calculate the sum of the elements in any collection object. The sum[] function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.

    Chủ Đề