 [Solved] Why is the output of the following code 6? | SoloLearn: Learn to code for FREE!

+2

# [Solved] Why is the output of the following code 6?

lst = [1,2,3,4] a = lst b = lst for i in range(0,5,2): a,b = b,a print(a+b) My confusion is in line 4, 5 and 6

+6

Read my added comments below: lst = [1,2,3,4] a = lst # a = 2 b = lst # b = 4 for i in range(0,5,2): #loop 3 times a,b = b,a # swap a and b (3X) print(a+b) # add 4+2 and print # result is 6

+8

As the swapping of the variables does not change anything: the 2 values to add are always a + b, and that gives 6. It does not matter how often the swapping is applied. So you could remove the line with the for loop and the line with swapping, this is only to confuse the reader in this case.

+6

lst = 2 lst = 4 Doesnt matter how you swap em, 2+4 is 6

+5

Thanks for your support Slick and Brian !!!

+3

yeah it just switches them a few times. But it doesnt matter cause your adding them anyways

+2

Rahul Hemdev yes 0,2,4. When it reaches 6, the range stops because 6 >= 5.

+2

+2

+1

Slick So does the for statement switch the values?

+1

Brian 3 times because range(0,5,2) = 0,2,4 ???