Skip to content

Question 18

Given the following function that takes in two lists:

def bar(la, lb):
    if not la and not lb:
        return []
    out = []
    if len(la) > len(lb):
        out.append(la[0])
    elif lb:
        out.append(lb[0])
    else:
        print('Pass')
    return out

Which of the following statements about bar(la, lb) is false?

  • The function will never print False
  • The returned list has at most one element
  • The list out is guaranteed to be non-empty when it is returned at the end of the function
  • The function is equivalent to (lb+la)[0] whenever lb has more elements than la
  • None of the above statements are false
Hint

It seems that the function bar() here takes in iterable values for both la and lb. If you're stuck with how to go about this, try a couple of paired iterable values for la and lb and see if any of the given statements manage to be false.

Solution

Before plugging in values, let's observe the logic behind this function bar(). The outcomes of this function would be to return a list, and on occasion perhaps print 'Pass'. We can deduce that the function will never print False, hence OPTION 1 is incorrect.

SCENARIO 1: Suppose we assign la = [1, 2] and lb = [3, 4, 5].

  • if not la and not lb: False, skip if block
  • We define out = [] to be returned at the end.
    • if len(la) > len(lb): False, skip this if block
    • elif lb: True (since lb is not empty), append lb[0] = 3 to out
  • Return out = [3]. This output list contains 1 element and is not empty.
  • OPTION 4: The function is equivalent to (lb+la)[0] whenever lb has more elements than la is True, hence this is incorrect.

SCENARIO 2: Suppose we assign la = [1, 2, 3] and lb = [4].

  • if not la and not lb: False, skip if block
  • We define out = [] to be returned at the end.
    • if len(la) > len(lb): True (len(la) = 3 is larger than len(lb) = 1), append la[0] = 1 to out
  • Return out = [1]. This output list contains 1 element and is not empty.

SCENARIO 3: Suppose we assign la = [] and lb = [].

  • if not la and not lb: True (len(la) = len(lb) = 0), return []. This output list contains no elements and is empty. Note that we did not declare or define a list called out in this procedure.

Notice that in each scenario, the output will always be either an empty list or a list with only 1 element. Additionally, when out is declared and defined, it will always end up with 1 element in it. Therefore, we can conclude that OPTION 2: The returned list has at most one element and OPTION 3: The list out is guaranteed to be non-empty when it is returned at the end of the function are True, thus both being incorrect.

Hence, none of the above statements are false. OPTION 5: None of the above statements are false is the correct answer.

Answer

None of the above statements are false