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.

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
220,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.

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
220,646 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