0

I tried to run the following python code, but I'm constantly getting "IndexError: list index out of range". I'm pretty sure that all the 'i' values are within the range of the list, I verified it by printing them at each iteration. I need help debugging it. Thanks!

list = [1, 2, 4, 0, 0, 7, 5]
new_list = []
length = len(list)
for i in range(length):
    if list[i] == 0 or list[i] == 7:
        list.pop(i)
        new_list.append(list[i])
    else:
        pass
print(new_list)
  • 2
    Naming your list `list` is a really bad idea. – o-90 May 09 '21 at 12:23
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – L.Grozinger May 09 '21 at 12:25

2 Answers2

2

Carefull! You are using the list build-in as your variable name. Also pop() is changing your list length. Keeping your idea a working solution could look like this:

mylist = [1, 2, 4, 0, 0, 7, 5]
new_list = []
length = len(mylist)
i = 0
while i < length :
    if mylist[i] == 0 or mylist[i] == 7:
        mylist.pop(i)
        new_list.append(mylist[i])
        length -= 1
    
    i += 1
print(new_list)

More pythonic would be using list comprehension:

mylist = [1, 2, 4, 0, 0, 7, 5]

new_list = [ i for i in mylist if i in [1, 7]]
mylist = [ i for i in mylist if not i in [1, 7]]
user_na
  • 2,154
  • 1
  • 16
  • 36
  • Thanks But in this case I can't really use the list comprehension as it doesn't really serve the purpose of the original code. – Gnaneshwaar May 09 '21 at 12:38
-1

I thought the variable name is not good but is this satisfied you if you delete this line:

list = [1, 2, 4, 0, 0, 7, 5]
new_list = []
length = len(list)

for i in range(length):
    print(list[i])
    if list[i] == 0 or list[i] == 7:
        new_list.append(list[i])
    else:
        pass

print(new_list)

I also a beginner for python. Check my code if you have time, thanks.

Yuki_N
  • 1