How to add number to each element in a list in Python
This Python tutorial will show you how to add a number to each element in a list in Python. In some situations, you may have to increment each element in a list in Python by a specific integer. This Python tutorial will help you to understand how easily you can add a specific number to every element in a list.
Add a number to each element in a list in Python
Let’s understand this with an example first then we will explain our code.
example_list = [45,12,4,96,41]
This is an example of a list. Now we will add an integer to each element in this list.
In order to perform this task, we will use the below program.
example_list = [45,12,4,96,41] print(example_list) incremented_list = [z+3 for z in example_list] print(incremented_list)
$ python codespeedy.py [45, 12, 4, 96, 41] [48, 15, 7, 99, 44]
You can see in the output that the original list is: [45, 12, 4, 96, 41]
And the incremented_list got each element increased by 3: [48, 15, 7, 99, 44]
So how we did this?
- Firstly we have taken a list.
- Then, we have printed the list. ( Just to show you the original list, this is not necessary )
- Now, we took another list variable, i.e, incremented_list to make a new_list where each element will be incremented by our desired integer. Here we have incremented by 3 using the below line of code:
incremented_list = [z+3 for z in example_list]
- Then we have printed the newly created list.
Here are some other tutorials,
Another way to perform this addition:
I know this is not related to list. But I can’t stop myself to share this as well.
If you are a Python developer or learner then you may be familiar with numpy library.
In this library, we have a similar object like list, which is known as array. But an array is different from a list.
The major difference between a numpy array and a list is,
- We can add any integer to each element in an array by using “+” operator. But we can’t do so with a list.
We will use this feature of an array to add a number to each element in a list.
import numpy as np example_list = [45,12,4,96,41] print(example_list) my_array = np.array(example_list) print(my_array + 3)
$ python codespeedy.py [45, 12, 4, 96, 41] [48 15 7 99 44]