Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop question
#1
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
Reply
#2
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.
Reply
#3
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())
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  A question about 'Event loop is closed' fc5igm 2 2,165 Oct-05-2021, 02:00 AM
Last Post: fc5igm
Exclamation question about input, while loop, then print jamie_01 5 2,616 Sep-30-2021, 12:46 PM
Last Post: Underscore
  for loop question KEYS 1 1,697 Oct-27-2020, 11:42 PM
Last Post: jefsummers
  Netmiko Loop question sc00ter 2 3,265 Oct-24-2020, 10:54 PM
Last Post: sc00ter
  while loop question KEYS 2 1,976 Sep-26-2020, 11:02 PM
Last Post: KEYS
  New to programming, loop question tomyan 1 1,590 Sep-25-2020, 04:32 PM
Last Post: Larz60+
  question about for loop Than999 5 2,427 Jun-09-2020, 02:16 PM
Last Post: Emekadavid
  Question about for loop not creating an infinite loop. FWendeburg 1 2,085 Feb-03-2019, 08:45 PM
Last Post: ichabod801
  Loop Condition Question malonn 6 3,417 Aug-01-2018, 01:56 PM
Last Post: malonn
  Beginner Loop question BigDisAok 5 3,661 Jul-24-2018, 02:04 PM
Last Post: BigDisAok

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020