Help with Logical error processing List of strings - 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: Help with Logical error processing List of strings (/thread-38801.html) |
Help with Logical error processing List of strings - dmc8300 - Nov-26-2022 This code is to remove one item from a List of "names" until the List is empty using for loop. The program does not complete the List stopping before the list is empty. See output 5 items on original List. Only 3 items removed # Simple Test to empty List using loop List_of_Users = ['josh', 'admin', 'cookie','jerry','jack'] # print("Starting List Below:") print(List_of_Users) Size_of_List = len(List_of_Users) print(f"The List contains {Size_of_List} members") for User in List_of_Users: List_of_Users.pop(0) print(f"The new List: {List_of_Users} ") Size_of_List = len(List_of_Users) print(f"The List contains {Size_of_List} members") print("")Output:
RE: Help with Logical error processing List of strings - Yoriz - Nov-26-2022 You should not alter a list you are iterating over, instead iterate a copy and alter the original. Change for User in List_of_Users:To for User in List_of_Users[:]: RE: Help with Logical error processing List of strings - deanhystad - Nov-27-2022 Ask yourself if you need to remove items from a list. I never do this. I build a new list that only contains the items I want to keep. If you think you need to remove all items, for is the wrong choice for your loop. while list_of_users: user = list_of_users.pop(0) # whatever RE: Help with Logical error processing List of strings - Larz60+ - Nov-27-2022 You can alter a list in place so long as you do it in reverse order: list_of_users = ['josh', 'admin', 'cookie','jerry','jack'] def pop_item(lname): if len(lname): lname.pop(len(lname)-1) while len(list_of_users): print(f"List length: {len(list_of_users)}, {list_of_users}") pop_item((list_of_users)) print(f"\nFinal length: {len(list_of_users)}")results:
|