0

I'm new to programming, please try to answer in simple words. This is my code

username = ['dante', 'ares', 'zues', 'death', 'admin']
if username:
    for user in username:
        if user == 'admin':
            print('Hello admin,would you like to see a status report?')
            username.remove(user)
        else:
            print(f"Welcome {user},hope you have a good time!")
            username.remove(user)
else:
    print("we need to find users!")

Output:

Welcome dante,hope you have a good time!
Welcome zues,hope you have a good time!
Hello admin,would you like to see a status report?

Expected Output:

Welcome dante, hope you have a good time!
Welcome ares, hope you have a good time!
Welcome zues, hope you have a good time!
Welcome death, hope you have a good time!
Hello admin, would you like to see a status report?
We need to find users!

  • 1
    You don't need to remove the names from the list while iterating - and as you can see, this leads to problems. – Thierry Lathuille Apr 05 '21 at 07:09
  • The thing is i dont understand the output behaviour! The output is not neccessary but the fact that 2nd and 4th user being missed is confusing.That remove method is supposed to remove the value of that particular object of loop on which loop is running but it is removing the next value.why? – Pavan Yeluri Apr 05 '21 at 11:11
  • You can find a short description of what happens when you remove items while iterating here: https://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list/ – Thierry Lathuille Apr 05 '21 at 11:28
  • The item you remove is always correctly removed. It's the iteration to the next one that doesn't work as you expect. – Thierry Lathuille Apr 05 '21 at 11:29
  • You can also find what the documentation says about it in [this answer](https://stackoverflow.com/a/34238688/550094) – Thierry Lathuille Apr 05 '21 at 11:31

1 Answers1

1
username = ['dante', 'ares', 'zues', 'death', 'admin']

for user in username:
    if user == 'admin':
        print('Hello admin, would you like to see a status report?  we need to find users!')
    else:
        print(f"Welcome {user},hope you have a good time!")