How to add a value to every element inside a list?

Viewed 77
value = int(input("Enter the value"))
my_list = [1,2,3,4,5]

If the input value is 5, I want to add 5 to every element in my_list where the expect outcome should be [6,7,8,9,10].

3 Answers

There are several ways:

value = int(input("Enter the value"))
my_list = [1, 2, 3, 4, 5]

# Using map()
new_list = list(map(lambda list_value: list_value + value, my_list))

# Using list comprehension
new_list = [list_value + value for list_value in my_list]

Or, if you are using numpy:

import numpy as np

value = int(input("Enter the value"))

my_list = np.asarray([1, 2, 3, 4, 5]) + value

That's very simple:

value = int(input("Enter the value"))
my_list = [1,2,3,4,5]
new_list = [x+value for x in my_list]

This basically creates a new list by iterating over the elements of the old one and adding value to them.

This method is called "list comprehension". It allows you to create new lists in a concise way. Common applications are to make new lists where each element is the result of some operations applied to each member of another list, or to create a subsequence of those elements that satisfy a certain condition. You can read more about it here.

you can use a simple for loop:

for i, e in enumerate(my_list):
    my_list[i] = value + e
print(my_list)

output(for input 5):

[6, 7, 8, 9, 10]

or you can use the built-in functions: map, sum and zip:

list(map(sum, zip(my_list, [value]*len(my_list))))

or you can use itertools.cycle

from itertools import cycle

list(map(sum, zip(my_list, cycle([value]))))
Related