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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With