23
X = [0,5,0,0,3,1,15,0,12]

for value in range(0,len(X)):

    if X[value] <= 0:
        del X[value]
        print(X)
print(X)

I run the code but then i get an error saying that the list is out of index range. Can someone please help me out on how to correct this mistake

3
  • 3
    [i for i in X if i != 0] Commented Apr 23, 2018 at 5:09
  • 1
    You have your data structures mixed up- del X[value] is what you would use if you were accessing a dictionary, X is a list Commented Apr 23, 2018 at 5:19
  • Thanks. I recently started programming so i dont know the differences. But thanks for the help. I really appreciate it. I have to learn these stuff for my exam on Tuesday Commented Apr 23, 2018 at 5:30

2 Answers 2

51

Try a list comprehension.

X = [0,5,0,0,3,1,15,0,12]
X = [i for i in X if i != 0]
Sign up to request clarification or add additional context in comments.

Comments

14
>>> X = [0,5,0,0,3,1,15,0,12]
>>> list(filter(lambda num: num != 0, X))
[5, 3, 1, 15, 12]

2 Comments

Thanks. And I have a question. I have seen the function lambda on multiple questions. What does it actually do. Thanks
lambda functions are one line anonymous functions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.