adding numbers in a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: adding numbers in a list (/thread-32015.html) |
adding numbers in a list - Nickd12 - Jan-15-2021 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] RE: adding numbers in a list - bowlofred - Jan-15-2021 25 plus the last number plus the spot on the first list? What would be the answer if the first list were [5, 10]? RE: adding numbers in a list - Serafim - Jan-15-2021 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] >>> |