0

Define a function that accepts a list (called numbers below) as input and return a list where each element is multiplied by 10. The grader will supply the argument numbers to the function when you run the grader.score.in__problem2 method below.

In this case, you need to write a function that will work for arbitrary input. Before submitting your function to the grader, you may want to check that it returns the output that you expect by evaluating code similar to the following:

test_numbers = [1, 2, 3]
mult(test_numbers)

I am relatively new to coding and i am finding it hard to come up with a proper solution

def mult(numbers):
    return (10) * len(numbers)

i expect output to be (10, 20, 30) but i only get 30 as a response

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 2
    Possible duplicate of [Apply function to each element of a list](https://stackoverflow.com/questions/25082410/apply-function-to-each-element-of-a-list) – DeepSpace Jul 11 '19 at 12:16
  • `len(...)` returns the **len**gth of a list, which is why you are getting 30 (10 * 3) – DeepSpace Jul 11 '19 at 12:16
  • okay that part i understand now, but i am struggling in finding a way to multiply the numbers in the array and returning it in the appropriate format and i have been at it for hours now – Brian Demadema Jul 11 '19 at 12:20
  • @BrianDemadema look at using [list comprehension](https://www.pythonforbeginners.com/basics/list-comprehensions-in-python) – blackbrandt Jul 11 '19 at 12:29
  • Thank you, will have a look at it – Brian Demadema Jul 11 '19 at 12:35

5 Answers5

2

You can use list comprehension:

def mult(my_list):
    return [10*n for n in my_list]
>>> m = [1,2,3]
>>> mult(m)

[10,20,30]
blackbrandt
  • 2,010
  • 1
  • 15
  • 32
0

There is a built-in function called map that does this.

Return an iterator that applies function to every item of iterable, yielding the results.

As example for what you want to do:

test_numbers = [1, 2, 3]
print(list(map(lambda x: x*10, test_numbers)))
# [10, 20, 30]

If you need to code it yourself you need to iterate over your list. For that we use the keyword for.

new_list = []
test_numbers = [1, 2, 3]
for number in test_numbers:
    new_list.append(number * 10)
print(new_list)
# [10, 20, 30]

For each iteration, number is evaluating to each item in the list (first iteration is 1, second is 2, third is 3).

palvarez
  • 1,508
  • 2
  • 8
  • 18
0

You can use for to iterate over your array list:

test_numbers=[1,2,3]
for var in test_numbers:
  print (##test_numbers.index(var),
         var*10)
Yorki
  • 135
  • 13
0

You could write as follows:

def multiply(numbers):
    return [item*10 for item in numbers]

numbers= [1, 2, 3]
multiply(numbers)
nurealam siddiq
  • 1,567
  • 10
  • 9
0
new_numbers=[]
def mult(numbers):
    for number in numbers:
        new_number = number*10
        new_numbers.append(new_number)
    return new_numbers