1
L=[10,19,20,30,8,11,9]
i=0
while i==0:
    while L[i]<=12:
        i+=1
    else:
        L.pop(i)
        i=0

Hello, I want to remove values, which are bigger than 12, from the list. I get the list I want, but I also get an error message, which says "list index out of range" even though I make i=0 at the end of loop. How can I fix it?

blitz1
  • 77
  • 5
  • Does this answer your question? [List comprehension vs. lambda + filter](https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter) – Constantin Guidon Sep 19 '20 at 18:04
  • 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) – Wups Sep 19 '20 at 18:04

6 Answers6

3

You can do, using a conditional list comprehension:

l=[each for each in L if each<=12]

l will be:

[10, 8, 11, 9]

If you don't like list comprehension, you can do:

l=[]
for each in L:
    if each<=12:
        l.append(each)

l will be the same as before.

zabop
  • 6,750
  • 3
  • 39
  • 84
2

When you do a pop(), you are changing the list by shortening it. If you want to do the pop() call, I suggest parsing the list in reverse order, starting at the end and working towards the beginning.

for i in range(len(L) - 1, -1, -1):
    if L[i] > 12:
        L.pop(i)

But, to directly answer your question, change your code to replace:

L.pop(i)

with:

if i < len(L):
    L.pop(i)

That should make your actual error go away. But it's not the best way to handle the problem. I would still suggest processing the list in reverse order.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32
  • And although a list comprehension is a better way to implement this problem, it may not be the best solution for a newer coder. – GaryMBloom Sep 19 '20 at 18:39
2

You can use filter:

L=[10,19,20,30,8,11,9]

#For python 2
L1 = filter(lambda x: x < 12, L)

#For python 3, wrap filter with list
L1 = list(filter(lambda x: x < 12, L))

print (L1)
Homer
  • 424
  • 3
  • 7
1

A solution with while and without creating a new list

L=[10,19,20,30,8,11,9]
i=0
while i < len(L):
    if L[i] > 12:
        L.pop(i)
    else:
        i += 1
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
  • I would prefer using @zabop's [suggestions](https://stackoverflow.com/a/63971813/14277722). It's usually not a good idea to manipulate a list inplace. – Michael Szczesny Sep 19 '20 at 18:12
0

though this is not the best way of doing it, but it may be the desired fix you are looking for

L=[10,19,20,30,8,11,9]
i=0
while i==0:
  while L[i]<=12:
    if i==len(L)-1:
      break
    i+=1
  else:
    L.pop(i)
    i=0
-1

Try pandas for simpler answer

import pandas as pd
df = pd.DataFrame({'A': [10,19,20,30,8,11,9]})
final_list = df[df['A'] <= 12]['A'].values.tolist()

Simplest answer

Ajay A
  • 1,030
  • 1
  • 7
  • 19