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.
#3
Thanks for you help, but I figured it out without setting the variables. I forgot it was the sum of the first n numbers.

def sum_first_n_nums(lst, n):
	if n <= len(lst):
		return sum(lst[0:n])
	elif n > len(lst):
		return sum(lst)
Reply


Messages In This Thread
RE: Return the sum of the first n numbers in the list. - by pav1983 - Jun-24-2020, 02:50 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,565 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  How to sort a list with duplicates and return their unique indices. Echoroom 3 3,752 Sep-23-2022, 07:53 AM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 3,175 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  numbers in list - max value and average stewie 2 2,922 Apr-01-2020, 06:25 PM
Last Post: buran
  Question about Sorting a List with Negative and Positive Numbers Than999 2 12,983 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  list of odd numbers cffiver2 2 5,303 Jul-12-2019, 09:46 AM
Last Post: perfringo
  Methods that return the highest score from the list erfanakbari1 7 7,419 Mar-26-2019, 08:32 PM
Last Post: aankrose
  Return not vowels list erfanakbari1 2 2,805 Mar-26-2019, 11:37 AM
Last Post: perfringo
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 2,363 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,208 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