Praveen Sripati Praveen Sripati - 2 months ago 17
Python Question

While statement and expressions

while
loop statement gets executed as long as the expression is true.

After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list. But, the below code executes fine without any error. Why is it so?

a = [x*x for x in range(10)]
while a.pop():
print("elements in the list")


It might be a very basic question, but I am trying to get comfortable with Python.

Answer

After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list.

No, the code never tries to do any pops after the 10th, because the 10th pop returns 0. 0 is considered false in a boolean context, so the loop terminates at that point.