Skip to content

Question 41

Given a list L of integers, complete function mul_list() with valid Python expressions/statements such that it returns a list that contains all the integers in L multiplied by n.
e.g., if L = [1,3,9] and n = 4, the function should output [4,12,36].

def mul_list(L, n):
    return _____1_____

Here is a sample run:

>>> print(mul_list([1,3,9,2,4,7],2))
[2, 6, 18, 4, 8, 14]

Note that your code needs to be syntactically correct to gain marks. You cannot use any semi-colon(;) and we will deduct marks if your answer is too long.

Model Solution

Hint 1

You will need list comprehension for this question. What you can try to do is work out the solution without it first using a regular loop structure before converting it into its list comprehension equivalent.

Hint 2 (read Hint 1 first!)

Compress the highlighted lines 2-5 into one line.

1
2
3
4
5
def mul_list(L, n):
    output = []
    for i in L:
        output.append(i*n)
    return output
Model Solution
def mul_list(L, n):
    return [i*n for i in L]

Blank 1: [i*n for i in L]

Other acceptable answer(s):

  • list(map((lambda i: i*n), L))