Nov-22-2020, 09:42 PM
(This post was last modified: Nov-22-2020, 09:42 PM by deanhystad.)
It would be better if you figure it out yourself. I suggest studying the "while" loop version. Pay close attention to how the index (i) changes, how the len(users) changes, and why this stops the loop after removing only three users.
The for loop has the same problem as the while loop. The only difference is the for loop does not expose the index it is using to increment through the loop.
Here's another way to delete all the users:
And it should be obvious by now why this doesn't work. It is very similar to the previous version with one critical difference.
The for loop has the same problem as the while loop. The only difference is the for loop does not expose the index it is using to increment through the loop.
Here's another way to delete all the users:
users = ['0', '1', '2', '3', '4'] print('\nfor i in range(len(users)):') for i in range(len(users)): print('delete ', users[0], 'from', users, 'i =', i) del users[0] print('users =', users)
Output:for i in range(len(users)):
delete 0 from ['0', '1', '2', '3', '4'] i = 0
delete 1 from ['1', '2', '3', '4'] i = 1
delete 2 from ['2', '3', '4'] i = 2
delete 3 from ['3', '4'] i = 3
delete 4 from ['4'] i = 4
From the output it is obvious that len(users) is only evaluated once.And it should be obvious by now why this doesn't work. It is very similar to the previous version with one critical difference.
users = ['0', '1', '2', '3', '4'] print('\nfor i in range(len(users)):') for i in range(len(users)): print('delete ', users[i], 'from', users, 'i =', i) del users[i] print('users =', users)
Output:for i in range(len(users)):
delete 0 from ['0', '1', '2', '3', '4'] i = 0
delete 2 from ['1', '2', '3', '4'] i = 1
delete 4 from ['1', '3', '4'] i = 2
Traceback (most recent call last):
File "C:\Users\djhys\Documents\python\musings\junk.py", line 28, in <module>
print('delete ', users[i], 'from', users, 'i =', i)
IndexError: list index out of range