I just learned while loops in Python, and would like some help in why the following two codes have different outputs. Since the while loop stops at iteration at when the squares element is not 'orange', I thought the output for both should be ['orange', 'orange']. Could you please explain the difference between two?
# code1
squares = ['orange', 'orange', 'red']
new_squares = []
i=0
square=squares[0]
while(square=='orange'):
new_squares.append(square)
square=squares[i]
i = i + 1
print(new_squares)
# code2
squares = ['orange', 'orange', 'red']
new_squares = []
i = 0
while(squares[i] == 'orange'):
new_squares.append(squares[i])
i = i + 1
print (new_squares)
-- EDIT --
If I were to change the order of the first code to as suggested in one of the answers, the output for is now ['orange', 'orange', 'red']. Why does 'red' get appended to the output if it fails the condition?
And so if I wanted to change the first code to have the output of ['orange', 'orange'], what would I have to do?
# code1
squares = ['orange', 'orange', 'red']
new_squares = []
i=0
square=squares[0]
while(square=='orange'):
square=squares[i]
new_squares.append(square)
i = i + 1
print(new_squares)