Python Forum

Full Version: Help with Logical error processing List of strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
Output:
Starting List Below: ['josh', 'admin', 'cookie', 'jerry', 'jack'] The List contains 5 members The new List: ['admin', 'cookie', 'jerry', 'jack'] The List contains 4 members The new List: ['cookie', 'jerry', 'jack'] The List contains 3 members The new List: ['jerry', 'jack'] The List contains 2 members [Finished in 254ms]
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[:]:
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
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:
Output:
List length: 5, ['josh', 'admin', 'cookie', 'jerry', 'jack'] List length: 4, ['josh', 'admin', 'cookie', 'jerry'] List length: 3, ['josh', 'admin', 'cookie'] List length: 2, ['josh', 'admin'] List length: 1, ['josh'] Final length: 0