Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Sahil Kapoor8,932 Points
" .remove()" funtion not correctly working inside a loop
PRINT EVEN INDEX NUMBERS ''' python list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in list : if list.index(num) %2 != 0: list.remove(num)
print(list) ''' Wanted output [1, 3, 5, 7, 9,]
Getting output [1, 3, 4, 6, 7, 9, 10]
".remove()" is not removing the odd index numbers as it is supposed to do in the code tell me if there is some error in the code or not ?
Steven Parker220,646 Points
The remove function is not the issue.
But when you iterate on something in a loop, and alter that thing while inside the loop, it can have side-effects such as causing elements to be skipped over.
To avoid this, you could iterate on a copy of the thing, or use a different strategy to accomplish the goal.