0
IndexError: list assignment index out of range 

SO ,I want to delete any element of numList that is greater than 3, but throws me an error. Any idea on this?

from datetime import datetime, date,timedelta
numList = [[2],[3],[4]]
for lst in numList:
for i in lst:
    if i > 3:
        print(i)
        del numList[i] # del numList[2] I dont want to use this 
                       #because numList elements are changing
        print("updated numList:",numList)  
Glenn Ford
  • 45
  • 8

2 Answers2

1

I can use this in list comprehension:

[y for x in numList for y in x if y < 3]

Will give another list of

[2,3]

Get it into a variable and then iterate over it. (enclose first y to [y] to get [[2],[3]])

Wasif
  • 14,755
  • 3
  • 14
  • 34
1

This should help u:

from datetime import datetime, date,timedelta
import copy 
numList = [[2],[3],[4]]
numListcopy = copy.deepcopy(numList) #Take a copy of the original list
for lst in numListcopy: #Iterate over the copied list
    for i in lst:
        if i > 3:
            print(i)
            del numList[numList.index(lst)]
print("updated numList:",numList) 

Output:

updated numList: [[2], [3]]
Sushil
  • 5,440
  • 1
  • 8
  • 26