0
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? )

Edited by Nick Evan: Add code-tags

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by snippsat
0

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? )

Post your code like this:

[code]

... code here

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

0

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]
'''

Edited by snippsat: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.