Skip to content

Question 30

Given the following code:

1
2
3
4
5
6
def foo(x, ds):
    l = []
    for k, v in ds.items():
        if v == x:
            l.append(k)
    return l

Which of the following statements is true about the list l returned by foo(x, ds)?

  • len(l) == len(set(l))
  • len(l) > 0 == True only if x in ds == True
  • l is an empty list if ds.get(x) returns None
  • l is equivalent to [ds[x]]
  • All of the above
Solution

Assume x is either an int, float, string (some primitive value), and ds is a dictionary. For simplicity, let's assume ds = {'a': 1, 'b': 2, 'c': 3, 'd': 1, 3: 'c'} and consequently x is either an integer or string value.

  • The if statement in the for loop assumes that if a value v stored in dictionary ds is equal to x, then we add its key k into l.
  • l will very likely contain keys of dictionary ds. For example, foo(2, ds) will return ['b']. This would not be the same as ds[x], as you're treating a compared value v as a key. Hence, OPTION 4: l is equivalent to [ds[x]] is incorrect. Consequently, OPTION 5: "All of the above" is also incorrect.
  • x in ds is effectively the same as checking if any value v is a key in ds - while this holds if x = 'c' or x = 3, this will not work for the other key-value pairs in ds. Hence, OPTION 2: len(l) > 0 == True only if x in ds == True is incorrect.
  • foo() adds keys k into l if the corresponding value v is equals to x, the latter of which is not the same as ds.get(x), which tries to check if a value v is a key in ds, return the corresponding value ds[x] if any and None otherwise. Hence, this is not indicative of how many elements l will have. Therefore, OPTION 3: l is an empty list if ds.get(x) returns None is incorrect.
  • Dictionaries work such that every key value is distinct. Given this logic, since l will very likely contain keys of dictionary ds, the length of l would be the same even if converted into a set. Hence, OPTION 1: len(l) == len(set(l)) is correct.

NOTE: This is a tough one, I understand if you can't wrap your head around this one. 😅

Answer

len(l) == len(set(l))