``````L = [ 0 , 2, 1 , -1 , -1 , -1, -1 ]

for i in L:
if i <= 0:
L.pop ( i )

print L``````

What I was expecting was that L = [ 0, 2, 1 ]
but the result was [ 2 , 1 , -1, -1 ]

I would like to know why it is such.

( I would also like to directly post python code over here, but I don't know how? )

All 2 Replies

What I was expecting was that L = [ 0, 2, 1 ]
but the result was [ 2 , 1 , -1, -1 ]

I would like to know why it is such.

You're using the pop() method of a list. It pop's a value from a list at INDEX x, not a VALUE x. So when you say that `if i is smaller then 0: pop i` You're removing the item at INDEX i. So when i == -1, python will try to pop at INDEX -1, which doesn't exist.

( I would also like to directly post python code over here, but I don't know how? )

[code]

... code here

[/code]
If you'd read the rules, you would have known this.

What I was expecting was that L = [ 0, 2, 1 ]

If you what this result is better to iterate over the list and append the result to a new list.

``````L = [ 0 , 2, 1 , -1 , -1 , -1, -1 ]

new_list = []
for item in L:
if item >= 0:
new_list.append(item)
print new_list
''' my output-->
[0, 2, 1]
'''

#Or more fancyer with list comprehension
lst = [item for item in L if item >= 0]
print lst
''' my output-->
[0, 2, 1]
'''``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.