Purify: Index out of Range


#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/purify?action=lesson_resume

<In what way does your code behave incorrectly? Include ALL error messages.>
Traceback (most recent call last):
File “python”, line 11, in
File “python”, line 6, in purify
IndexError: list assignment index out of range

<What do you expect to happen instead?>
Display an even list

```python

Replace this line with your code.

def purify(sequence):
  even_list = []
  count = 0
  for i in sequence:
    if (i%2 == 0):
      even_list[count] = i
      if(count <= len(sequence)-1):
        count += 1
  return even_list

print purify([2])
I am trying to write my own function here. Don't know what improvements are required here?

#2

even_list[count] = i can used to update an element in your list, but given there are no elements in the list, even even_list[0] will give an index error

why would you do this? What is the reasoning behind it? If you want to add to list, use append()

If the item is divisible by 2, we can just append to even_list, this is only one condition, not sure why you would have a second if condition


#3

I used second if condition to keep a check on the index and do not let it go out of bounds.
And append did worked for me, I was just trying to create my own functions to better understand the functionality.


#4

but this line:

even_list[count] = i

will throw an error, this is to update elements in list, but there are no elements in even_list, so it will always throw an error, and this is before the second if condition.

.append() is the way to go, if you use that method, you understand it well enough


#5

Ok. Thanks for your suggestions and help.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.