How can I remove all occurrences of one number in a list in Python

Viewed 5178

Just joined to ask this question as I cannot find it for the life of me on Google.

Say I have a list x = [1,1,1,2,3,3,4,5,5,5,6,7]

How can I remove all instances of the number 1 without deleting the index one by one?

tried del & remove but cannot seem to fathom it out.

Essentially what I am doing is counting all the occurrences of one number then removing it from my list.

ps. Cannot use: Remove all occurrences of a value from a list? as lambda isn't covered in our course.

I am not looking for code review so ignore some of my methods, just want to see if theres a way I can do this.


Edit: Thanks all, managed to get what I was after and complete my code. I've taken my code out just in case I am not allowed to post it on here.

2 Answers

Just use list comprehension:

x = [1,1,1,2,3,3,4,5,5,5,6,7]
x = [i for i in x if i != 1]

Output:

[2, 3, 3, 4, 5, 5, 5, 6, 7]

List Comprehension to the rescue.

x = [v for v in x if v != 1]
Related