Python Forum
For List Loop Issue - 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: For List Loop Issue (/thread-23453.html)



For List Loop Issue - Galdain - Dec-31-2019

Hello, good people of the Python forums! I am new to coding and Python both, it's nice to meet you all!

I am writing a simple program that compares a new user list against a current user list. After I made a copy of the original current user list I want to delete all of the values in it. I originally made a for loop to remove the items in the list but for some reason, it's skipping every other value. So it will remove jesse, bob, and justin. But alecs and Jameson will remain.

I have fixed it and instead have put in 'current_users.clear()' to clear out the list. Simpler and easier.

What I am having trouble with is understanding why the for loop is skipping over the items it does and was hoping to get some insight.

current_users = ['jesse', 'alecs', 'bob', 'Jameson', 'justin']

for current in current_users:
	print(current)
	current_users.remove(current)

print(current_users)



RE: For List Loop Issue - michael1789 - Dec-31-2019

It goes through the loop and deletes the first entry. Then the second entry becomes the first. Then it goes through the loop looking for the second entry, but the whole list is shifted over from when you removed the first entry.


RE: For List Loop Issue - Galdain - Dec-31-2019

(Dec-31-2019, 04:37 AM)Galdain Wrote: Hello, good people of the Python forums! I am new to coding and Python both, it's nice to meet you all!

I am writing a simple program that compares a new user list against a current user list. After I made a copy of the original current user list I want to delete all of the values in it. I originally made a for loop to remove the items in the list but for some reason, it's skipping every other value. So it will remove jesse, bob, and justin. But alecs and Jameson will remain.

I have fixed it and instead have put in 'current_users.clear()' to clear out the list. Simpler and easier.

What I am having trouble with is understanding why the for loop is skipping over the items it does and was hoping to get some insight.

current_users = ['jesse', 'alecs', 'bob', 'Jameson', 'justin']

for current in current_users:
	print(current)
	current_users.remove(current)

print(current_users)

Ahhhh, that makes sense now. I feel special, thank you very much!