The issue here is that you're modifying the list while iterating over it, which can have unexpected results.
When you iterate over a list using a for
loop, Python doesn't copy the list and iterate over a copy. Instead, it keeps track of the current position in the list and moves forward one element at a time. This is why you're not seeing the elements in the order you'd expect.
When you call usernames.remove(username)
, you're modifying the original list. However, this can cause problems because the loop is now iterating over a modified list. Specifically, when the loop moves to the next element, it starts from the next element in the modified list, not the next element in the original list.
To see why this is happening, imagine the list as a deck of cards. The for
loop is like a deck of cards with an index. The loop starts at the beginning of the deck, and each iteration moves the index to the next card. When you remove a card, the cards after that one shift down to fill the gap. So, when the loop moves to the next index, it's actually skipping over the card that was removed.
As for why it seems like it's skipping every other element, it's because the removal of elements shifts the indices of the remaining elements. For example, if you remove an element at index 2, the element that was previously at index 3 is now at index 2, and the element that was previously at index 4 is now at index 3. This can make it seem like elements are being skipped.
To avoid this issue, you can create a copy of the list and iterate over the copy while making changes to the original list. In your case, you could use a list comprehension to create a new list with the desired elements:
new_list = [user for user in usernames if user != 'Admin']
usernames[:] = new_list
Alternatively, you could iterate over the list in reverse order to avoid the issue:
for username in reversed(usernames):
if username == 'Admin':
usernames.remove(username)
In this case, since we're iterating over the list in reverse order, we can safely remove elements from the list without worrying about the indices shifting. This is because we're effectively "moving backwards" through the list, so we're not altering the indices of the elements we're still iterating over.