5

How do I add a number in my element?

lets say I want to add 10 to every single element in my array

I want my input to be [1,2,3,4,5] and my output to be [11,12,13,14,15]

This is what I came up with so far

def func(z):
        numbers = [1, 2, 3, 4,5]
        num = 10

    
        for i in z:
            numbers.append(i + num)
            i = numbers[-2:]
            return i

This prints 5,20 instead of 14 and 15.

2

5 Answers 5

10

Using a list comprehension is a fast, compact way of getting the answer that you want. It's a useful tool for you to learn to write better Python.

number_list = [1, 2, 3, 4, 5]

def add_num_to_each(num, number_list)
    return [ii + num for ii in number_list]

print(add_num_to_each(10, number_list))
>>> [11, 12, 13, 14, 15]
3

You can do it in a single line with map,

output_list = list(map(lambda x: x + 10, numbers))

Here 'numbers' is your input list.

3
numbers = [1, 2, 3, 4,5]

result = [item+10 for item in numbers]
2
import numpy as np
arr = np.array([1,2,3,4,5])
print(arr+10)

Using numpy Library is the smart choice as it reduce the time required to do vector calculation as compared to the iteration through loops.

2

You can use maps.

def addTen(n):
    return n+10

numbers = [1, 2, 3, 4, 5]
result = map(addTen, numbers)
print(list(result))
     

https://www.geeksforgeeks.org/python-map-function/

Not the answer you're looking for? Browse other questions tagged or ask your own question.