Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a number to every single element in python? [duplicate]

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.

like image 697
rc78 Avatar asked Nov 30 '22 21:11

rc78


1 Answers

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]
like image 139
jrmylow Avatar answered Dec 05 '22 05:12

jrmylow