Add Integer to Each Element in List in Python (3 Examples)
This Python article shows different ways to add an integer to each element in a list.
The article contains these contents:
Let’s dive into it!
Creating Example Data
We will create a sample list containing integers and floats by running the following code.
my_list = [1, 2.5, -3, 4.2, -5.7, 6] print(my_list) # [1, 2.5, -3, 4.2, -5.7, 6]
As you can see, my_list
is a list that contains six elements: three integers and three floats. Let’s see how to sum them with an integer!
Example 1: List Comprehension to Add Integer to Elements in List
Adding an integer to the values in a list can be achieved by using list comprehension. Take a look at the code below.
integer = 2 new_list = [x + integer for x in my_list] print(new_list) # [3, 4.5, -1, 6.2, -3.7, 8]
In the example above, we first defined an integer equal to 2. Then we created the object new_list
, using a list comprehension that adds 2 to each item in my_list
. When we printed the final result, the new list with the elements increased by 2 was obtained. Let’s see other examples!
Example 2: For Loop to Add Integer to Elements in List
In this example, we will loop through each number in our list using the range() and the len() functions. Then, we will add our integer to each element in the list using the +=
operator.
integer = 2 for i in range(len(my_list)): my_list[i] += integer print(my_list) # [3, 4.5, -1, 6.2, -3.7, 8]
Great! Let’s see the last example.
Example 3: map() Function to Add Integer to Elements in List
In this last example, we will apply the map() and lambda functions to add the integer defined to each element in my_list
. The result is a map object, which we have converted to a list using the list() function.
integer = 2 new_list = list(map(lambda x: x + integer, my_list)) print(new_list) # [3, 4.5, -1, 6.2, -3.7, 8]
In this tutorial, we have shown three different ways to append an integer to a list. Choose the most suitable for you!
Video, Further Resources & Summary
Do you need more explanations on how to join an integer to each component in a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
The YouTube video will be added soon.
Furthermore, you could have a look at some other tutorials on Statistics Globe:
- Count Elements Using List Comprehension in Python
- Convert Priority Queue to List & Vice Versa in Python
- Convert List from Boolean to String in Python
- Change Index of Element in List in Python
- Learn Python
This post has shown how to add an integer to each element in a list in Python. Please let me know in the comments if you have any doubts or questions.
This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get further information about her academic background and the other articles she has written for Statistics Globe.
Statistics Globe Newsletter