how to add input value to every items in the list in python?

Hariharan_S :
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].

Riccardo Bucco :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216077&siteId=1