Python Forum
while loop question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: while loop question (/thread-29004.html)



while loop question - spalisetty06 - Aug-13-2020

How is that it is looping even without decrement operator? possibly a stupid question, but it is a question for me.
l = [10, 20, 30, 40]
while len(l) != 0:
print(l.pop)
Output:
40 30 20 10



RE: while loop question - bowlofred - Aug-13-2020

The program above doesn't produce that output. The body of the loop isn't indented properly, and the pop function is shown without parentheses, so it would just return the function object.

If you changed it instead to
l = [10, 20, 30, 40]
while len(l) != 0:
    print(l.pop())
Then it would match the output. The pop() method on a list both removes the final element and returns that element. In the loop above, this shortens the list and prints the final element. Since the list is being shortened, that provides the decrement.


RE: while loop question - buran - Aug-13-2020

let's start by saying that your code will produce IndentationError. After fixing it, you will enter infinite loop, because you don't call the pop method
so the code should be
l = [10, 20, 30, 40]
while len(l) != 0:
    print(l.pop())
list.pop() method will return element from list and delete it from the list. Thus it will reduce the len of the list.

The ideomatic code would not check the len, but will use the True value of non-empty list
spam = [10, 20, 30, 40]
while spam:
    print(spam.pop())