Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Sahil Kapoor
Sahil Kapoor
8,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 ?

2 Answers

Steven Parker
Steven Parker
229,744 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.

Sahil Kapoor
Sahil Kapoor
8,932 Points

Can you please tell me the best way to print the desired output as I am getting the same problem quite offen

Sahil Kapoor
Sahil Kapoor
8,932 Points

Thanks steven to copy and then use the iterable worked thank you so much

Steven Parker
Steven Parker
229,744 Points

Another way would be to generate the items you want instead of removing ones you don't want, and then replace the list with that:

list = [list[i] for i in range(len(list)) if not i % 2]

An advantage of this approach is that it would work even if the list contents had repeated values.

Sahil Kapoor
Sahil Kapoor
8,932 Points

It worked thanks alot for the help Steven