0

I have this list : l = [2, 8, 1, 9, 11, 12, 3]. I want to remove elements that is greater than 5 in my list.

My code look like this:

l = [2, 8, 1, 9, 11, 12, 3]
for x in l:
    if x > 5:
        l.remove(x)
print(l)

But I am getting output as : [2, 1, 11, 3] I am using anaconda IDE. Please refer to image for more detail.

  • 3
    You should not be altering the list length while iterating over it. Instead you should build a new list with the items you want to keep – roganjosh Sep 14 '18 at 11:05
  • 1
    you are removing elements from the list you are iterating over! that is rarely a good idea! have a look at [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html?highlight=comprehension#list-comprehensions). – hiro protagonist Sep 14 '18 at 11:05
  • A side note, Anaconda is not an IDE. It is a distribution of Python. Spyder is the IDE that comes with Anaconda. – roganjosh Sep 14 '18 at 11:09
  • The funny thing is that this question is a duplicate of a question that is a duplicate of a question that is a duplicate of a question XD –  Sep 14 '18 at 11:13
  • @SembeiNorimaki yep, this particular dupe is pretty circular. I just go for one that I think is a decent starting point in the loop. IIRC I did find the bottom of the spiral and it wasn't particularly great, better to start somewhere higher up and the OP can work their way through – roganjosh Sep 14 '18 at 11:14
  • @SembeiNorimaki added the original of the duplicates. i think the answers there are more helpful here... – hiro protagonist Sep 14 '18 at 11:18
  • Thank you for the answers. But what if the problem is to solve without creating any extra list?? And whats wrong with logic in above code? Can you please explain. I could not get it. – Ramesh Pradhan Sep 14 '18 at 11:27
  • The linked answers already explain it in far more detail than we can do again. There's also another dupe: https://stackoverflow.com/a/6260097/4799172 that illustrates the issue, which you could get to from the initial dupe I linked – roganjosh Sep 14 '18 at 11:46

1 Answers1

1

As said in the comments, it's not the safest way to do it. Try this instead:

l = [2, 8, 1, 9, 11, 12, 3]
m =[]
for x in l:
    if x <= 5:
        m.append(x)
print(m)

Output:

[2, 1, 3]
Piotrek
  • 1,400
  • 9
  • 16