How To Add A Number To Each Element In An Array Python

In this tutorial, we will learn how to add a specific number to each element of an array in Python. This task can be achieved using various approaches such as list comprehension, the map() function, or by simply looping through the array using a for loop. By the end of this tutorial, you should be able to perform this operation efficiently using any of these methods.

Step 1: Creating an Array

First, we need an array to work with. You can create a list in Python using square brackets [] and separating the elements by commas. For this tutorial, we will use the following list:

Step 2: Adding a Number using List Comprehension

List comprehension is a concise way to create or modify lists in Python. It allows us to generate a new list by applying an expression to each element of the existing list.

To add a number to each element in the array using list comprehension, we can do the following:

Here, x is a variable that represents each element in the array, and number_to_add is the number we want to add to each element of the array. The list comprehension iterates through each element in arr, adds the value of number_to_add to it, and creates a new list using the resulting values.

Step 3: Adding a Number using the map() Function

The map() function is another way to apply a specific operation to every element of an iterable. In our case, we will use the map() function to add a number to each element of the array. Here’s how we can do that:

In this approach, we first define a function called add_number() that takes an array element as its argument and returns the element after adding the specified number. Then, we use the map() function along with the add_number() function to apply our operation to each element of the array. Finally, we use the list() function to convert the result back into a list since the map() function returns a map object.

Step 4: Adding a Number using a For Loop

Alternatively, you can simply use a basic for loop to add a number to each element in the array. Here’s how you can achieve that:

In this approach, we create an empty list called new_arr. We then loop through each element of the array, add the specified number to each element, and append the result to the new_arr list.

Full Code:

Output:

[6, 7, 8, 9, 10]

Conclusion

In this tutorial, we learned how to add a specific number to each element of an array in Python using list comprehension, the map() function, and a for loop. Each method has its advantages, so you can choose the one that suits your needs according to readability, performance, or personal preference.