def mult(numbers):
return [10] * len(numbers)
number = [1,2,5,6,7,8,10]
mult(number)
I expect the output of [10,20,50.......]
but this is the output I'm getting [10, 10, 10, 10, 10, 10, 10]
def mult(numbers):
return [10] * len(numbers)
number = [1,2,5,6,7,8,10]
mult(number)
I expect the output of [10,20,50.......]
but this is the output I'm getting [10, 10, 10, 10, 10, 10, 10]
Here's what you're doing, annotated:
def mult(numbers):
return [10] * len(numbers)
# [10] --> Take the list [10]
# len(numbers) --> Take the length of the list `numbers`, which has 7 elements
# [10] * len(numbers) --> repeat [10] seven times, to get [10, 10, 10, 10, 10, 10, 10]
I think the problem is you're misunderstanding what the len()
function does, and how the *
(multiplication) operator works with lists. If you want to multiply each number by 10, you would do something like this:
def mult(numbers):
multed = [] # create an empty list to store the result
for num in numbers: # iterate through the elements in `numbers` one by one
multed.append(10 * num) # add (10 * element) to our new list
return multed # return the list we've created
Python also has list comprehensions that make this code more concise:
def mult(numbers):
return [10*num for num in numbers]
# this does the same thing as above
This is how I would do it
def mult(numbers):
return [10*i for i in numbers]
number = [1,2,5,6,7,8,10]
mult(number)
Your approach is simply taking the value 10
and copying a number of times equal to the len
of your input array.
I think you should try this way.
def mult(number):
return 10 * number
number = [1,2,5,6,7,8,10]
answer = []
for i in number:
answer.append(mult(i))
print(answer)