Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding numbers in a list
#1
what im looking to do is add 25 to elements in a list but add 25 plus the last number

example

list = [0,0,0,0]

i want the output to be

list = [0,25,50,75]
Reply
#2
25 plus the last number plus the spot on the first list? What would be the answer if the first list were [5, 10]?
Reply
#3
If I follow the example
>>> def add_num_to_list(lst, num): ... new_list = [lst[0]] ... for i in lst[1:]: ... new_list.append(i+num+new_list[-1]) ... return new_list ... >>> print(add_num_to_list([0,0,0,0], 25)) [0, 25, 50, 75] >>> print(add_num_to_list([5,10], 25)) [5, 40]
Where the last printout is an answer to the question asked by @bowlofred

But if I follow the text description:
>>> def add_num_to_list(lst, num): ... new_list = [] ... for i in lst: ... new_list.append(i+num+(new_list[-1] if new_list else 0)) ... return new_list ... >>> print(add_num_to_list([0,0,0,0], 25)) [25, 50, 75, 100] >>> print(add_num_to_list([5,10], 25)) [30, 65] >>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 24,110 Jan-05-2024, 08:30 PM
Last Post: sgrey
  find random numbers that are = to the first 2 number of a list. Frankduc 23 9,758 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Adding values with reduce() function from the list of tuples kinimod 10 7,428 Jan-24-2023, 08:22 AM
Last Post: perfringo
  List of random numbers astral_travel 17 7,558 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 5,423 Nov-13-2022, 01:27 AM
Last Post: menator01
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 3,868 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Divide a number by numbers in a list. Wallen 7 13,380 Feb-12-2022, 01:51 PM
Last Post: deanhystad
  producing numbers out of a list bouraque7878 10 7,101 Nov-12-2021, 09:13 PM
Last Post: jefsummers
  How to change odd to even numbers in the list? plumberpy 8 6,965 Aug-08-2021, 11:07 AM
Last Post: plumberpy
  convert numbers into list lokesh 1 3,506 Jun-03-2021, 06:37 AM
Last Post: menator01

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.