Home > Back-end >  How to create a function that multiples every elements in a list by any number when the function is
How to create a function that multiples every elements in a list by any number when the function is

Time:10-27

For example: (fill in the blank in the for loop)

my_list = [1,3,5,7,9]

def multiply_list_by(alist, multiplier):
    """
    Returns a new list that multiplies each element of alist
    by the multiplier, so that the new list is the same length
    as alist, and the n'th element of new_list is equal to
    multiplier times the n'th element of alist
    """
    new_list = []
    
    for elem in my_list():
        new_list.append(___)
    return new_list

Expected output

multiply_list_by(my_list, 10)
# the result should be [10, 30, 50, 70, 90]

CodePudding user response:

You can do it by list comprehension, but if you want to use loop, then use for loop. Using for loop, you can iterate the list, multiply each element with the multiplier and add it to another empty list say y, finally display y. Your code:

my_list=[1,3,5,7,9]
def multiply_list_by(my_list,multiplier):
    y=[]
    for i in my_list:
        y.append(i*multiplier)
    return y

print(multiply_list_by(my_list,10))

CodePudding user response:

The answer can be:

def multiply_list_by(alist, multiplier): return [a*n for a in alist]

CodePudding user response:

You can use a list comprehension:

def f(l,m):
 return [x*m for x in l]

print(f([1,3,5,7,9],10))
  • Related