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.

rc78
  • 65
  • 4
  • 1
    what is `z`? You also returning from loop in first iteration... simple `numbers = [n+10 for n in numbers]` is enough – Andrej Kesely Sep 19 '20 at 06:36
  • A better duplicate: [How to add an integer to each element in a list?](https://stackoverflow.com/q/9304408/7851470) – Georgy Sep 20 '20 at 00:00

5 Answers5

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]
jrmylow
  • 679
  • 2
  • 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.

Maran Sowthri
  • 829
  • 6
  • 14
3
numbers = [1, 2, 3, 4,5]

result = [item+10 for item in numbers]
Anjaly Vijayan
  • 237
  • 2
  • 9
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.

ASLAN
  • 629
  • 1
  • 7
  • 20
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/

Wilfredo
  • 137
  • 1
  • 9