+ 4

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

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

27th Sep 2020, 2:33 AM
Rahul Hemdev
Rahul Hemdev - avatar
10 Réponses
+ 7
Read my added comments below: lst = [1,2,3,4] a = lst[1] # a = 2 b = lst[3] # 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
27th Sep 2020, 2:42 AM
Brian
Brian - avatar
+ 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.
27th Sep 2020, 10:35 AM
Lothar
Lothar - avatar
+ 7
lst[1] = 2 lst[3] = 4 Doesnt matter how you swap em, 2+4 is 6
27th Sep 2020, 2:41 AM
Slick
Slick - avatar
+ 6
Thanks for your support Slick and Brian !!!
27th Sep 2020, 2:50 AM
Rahul Hemdev
Rahul Hemdev - avatar
+ 4
yeah it just switches them a few times. But it doesnt matter cause your adding them anyways
27th Sep 2020, 2:44 AM
Slick
Slick - avatar
+ 3
Rahul Hemdev yes 0,2,4. When it reaches 6, the range stops because 6 >= 5.
27th Sep 2020, 2:49 AM
Brian
Brian - avatar
+ 3
Brian Okay, thanks
27th Sep 2020, 2:50 AM
Rahul Hemdev
Rahul Hemdev - avatar
+ 2
Slick So does the for statement switch the values?
27th Sep 2020, 2:43 AM
Rahul Hemdev
Rahul Hemdev - avatar
+ 2
Brian 3 times because range(0,5,2) = 0,2,4 ???
27th Sep 2020, 2:45 AM
Rahul Hemdev
Rahul Hemdev - avatar
+ 2
Okay, thanks Lothar
27th Sep 2020, 1:53 PM
Rahul Hemdev
Rahul Hemdev - avatar