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
  convert numbers into list lokesh 1 402 Jun-03-2021, 06:37 AM
Last Post: menator01
  Adding a list to Python Emailing Script Cknutson575 4 556 Feb-18-2021, 09:13 AM
Last Post: buran
  Adding List Element if Second part of the List Elements are the Same quest_ 3 629 Nov-25-2020, 04:33 PM
Last Post: bowlofred
  Print max numbers in a list jimmoriarty 1 536 Sep-25-2020, 07:29 AM
Last Post: DPaul
  importing a list of numbers into python script barrypyth 8 1,277 Aug-22-2020, 09:10 PM
Last Post: barrypyth
  Summing a list of numbers Oldman45 6 834 Jul-12-2020, 05:30 PM
Last Post: Oldman45
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 6 6,025 Jul-01-2020, 03:53 PM
Last Post: ndc85430
  Append only adding the same list again and again viraj1123 4 731 Jun-17-2020, 07:26 AM
Last Post: viraj1123
  Topic: “Filter numbers with a list comprehension” (PyBite #107) Drone4four 4 841 Jun-11-2020, 08:31 PM
Last Post: Drone4four
  Assign the sum of 2 consecutive numbers in a list to a varibale Fenaz 3 812 Apr-05-2020, 10:30 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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