+ 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
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
+ 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.
+ 7
lst[1] = 2
lst[3] = 4
Doesnt matter how you swap em, 2+4 is 6
+ 4
yeah it just switches them a few times. But it doesnt matter cause your adding them anyways
+ 3
Rahul Hemdev yes 0,2,4. When it reaches 6, the range stops because 6 >= 5.
+ 3
Brian Okay, thanks
+ 2
Slick So does the for statement switch the values?
+ 2
Brian 3 times because range(0,5,2) = 0,2,4 ???
+ 2
Okay, thanks Lothar