KnowledgeBoat Logo
|

Computer Science

What will be the output of the following code ?

def process_data(lst, dct):
    result = []
    for i in lst:
        if i in dct:
            result.append(dct[i] * i)
        else:
            result.append(i ** 2)
    return result

lst = [1, 2, 3, 4]
dct = {2: 5, 3: 10}
print(process_data(lst, dct))

Python Functions

3 Likes

Answer

[1, 10, 30, 16]

Reason — In the function process_data(lst, dct), the code iterates through each element in the list lst. For each element i, it checks if i is present as a key in the dictionary dct. If i is found in the dictionary, it appends the value dct[i] * i to the result list. If i is not found in the dictionary, it appends i ** 2 (i squared) to the result list.

  • For i = 1, 1 is not in the dictionary, so 1 ** 2 = 1 is added.
  • For i = 2, 2 is in the dictionary, and dct[2] = 5, so 5 * 2 = 10 is added.
  • For i = 3, 3 is in the dictionary, and dct[3] = 10, so 10 * 3 = 30 is added.
  • For i = 4, 4 is not in the dictionary, so 4 ** 2 = 16 is added.

Thus, the final result is [1, 10, 30, 16].

Answered By

3 Likes