Python Forum
Return the sum of the first n numbers in the list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return the sum of the first n numbers in the list.
#4
If lst has less elements than n, sum returns the sum of the entire list.
def sum_first_n_nums(lst, n):
    return sum(lst[:n])
And since sum fixes things automatically there isn't any reason to write you own function.
Reply


Messages In This Thread
RE: Return the sum of the first n numbers in the list. - by deanhystad - Jun-24-2020, 03:37 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,545 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  How to sort a list with duplicates and return their unique indices. Echoroom 3 3,724 Sep-23-2022, 07:53 AM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 3,149 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  numbers in list - max value and average stewie 2 2,905 Apr-01-2020, 06:25 PM
Last Post: buran
  Question about Sorting a List with Negative and Positive Numbers Than999 2 12,960 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  list of odd numbers cffiver2 2 5,290 Jul-12-2019, 09:46 AM
Last Post: perfringo
  Methods that return the highest score from the list erfanakbari1 7 7,386 Mar-26-2019, 08:32 PM
Last Post: aankrose
  Return not vowels list erfanakbari1 2 2,774 Mar-26-2019, 11:37 AM
Last Post: perfringo
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 2,348 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,201 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020