Robotics & Artificial Intelligence

What would be the output of following code snippet:

a = [1, 2, 3, 4, 5] 
b = [2, 2, 2, 2, 2] 
for i in a: 
    for j in b: 
        k=i+j 
    print(k)

Python Control Flow

1 Like

Answer

Output:

3
4
5
6
7
Explanation
  • The outer for loop iterates through each element of list a.
  • For each value of i, the inner for loop iterates through all elements of list b.
  • Inside the inner loop, the value of k is updated as k = i + j. Since all elements of list b are 2, and k is overwritten in every inner iteration, after the inner loop finishes, k holds the value i + 2.
  • The print(k) statement is outside the inner loop but inside the outer loop, so it prints the final value of k for each i.

Iterations:

Outer Loop (i)Inner Loop (j) valuesCalculation (k = i + j)Value Printed
12, 2, 2, 2, 23, 3, 3, 3, 33
22, 2, 2, 2, 24, 4, 4, 4, 44
32, 2, 2, 2, 25, 5, 5, 5, 55
42, 2, 2, 2, 26, 6, 6, 6, 66
52, 2, 2, 2, 27, 7, 7, 7, 77

Answered By

2 Likes


Related Questions