Why can not I delete an object from a list in python?

4

I present my code:

numbers = list(range(0, 30, 2))
for i in range(0, 30):
    if numbers[i] % 2 == 0 and numbers[i] == 2:
        numbers[i] = 2 
    if numbers[i] % 2 == 0:
        numbers.remove(i)
print(numbers)
  
    
      

Traceback (most recent call last):         File "F: / python / list.", Line 7, in           numbers.remove (i)       ValueError: list.remove (x): x not in list

    
  
    
asked by Alvaro Newman gonzales 26.12.2016 в 19:45
source

2 answers

3

The first thing on your list is declaring the range 0-30 with step 2, that is, these three parameters:

  

start: Start the sequence number

     

stop: Generates numbers up to, but does not include this number

     

step: Difference between each number in the sequence

Therefore, you are indicating that there is a difference between each number of two, which would be 15 numbers. However, since the last one (the 30th) does not include it, in this case it would be 14 numbers.

The first error I see in your code is that the loop you are doing is doing from 0 to 29 and therefore there will be positions for numbers[i] that will not exist.

On the other hand, you are trying to delete an item that does not exist on your list. If you notice, you are always assigning value 2 to the elements in which you include something. However, you are trying to delete a value that does not exist (1, 2, 3, 4 ...) since your list is only composed of numbers 2 and you are trying to delete the iterator values, which in this case you do not store in your list and therefore can not delete.

    
answered by 26.12.2016 / 19:59
source
1

I think the problem is in the following:

>>>list(range(0,30,2))

will release a list with the following items:

>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

that is what is stored in your list. They are only 15 numbers all pairs. The for i in range (0,30) takes into account elements that are not even: (0,1,2,3 ... 29). Then your mistake is that you ask him to remove the index when it is not even.

I give you a clarifying example: in the first iteration the index is 0; when you reach the point of numbers.remove(i) ; i will value 0. For being the index; coincidentally, it is also the first item on your list. However in the second iteration; i takes the value 1; numbers [1] has assigned the value two, which according to your code enters the block:

if numbers[i] % 2 == 0:
        numbers.remove(i)

but .. how are you going to remove value 1? That number is not on the list. I hope this explanation has been useful. Greetings.

    
answered by 26.12.2016 в 20:16