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

For loop issue

Hi guys,

Can you please explain the last line of code in a bit more detail as I'm struggling to grasp this.

numbers = [0, 1, 2, 3, 4, 5] for number in numbers: numbers.remove(number) - #Struggling with this

1 Answer

numbers = [0, 1, 2, 3, 4, 5]

for number in numbers:
    numbers.remove(number)

print(numbers)

It's simple, you are iterating through the list of numbers, in every iteration an element of the list gets assigned to the 'number', meaning in first iteration 'number = 0' and in second iteration 'number = 1' and so on. This number is then passed as the list index in the remove method so in first iteration numbers.remove(number=0) it removes the first index in the numbers that is '0' in second iteration numbers.remove(number=1) and remember we have removed the first index so the list now is [1, 2, 3, 4,5] which means now the we have '2' at index 1 so in next iteration '2' gets removed and we are left with a list [1,3,4,5] and at next iteration we have number = 2 and we have '4' at index 2 so 4 gets removed and we are left with [1,3,5].

Hope this clarifies it for you.