3

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.

SamCramphorn
  • 143
  • 1
  • 2
  • 14
  • Uh, what is your function suppose to do? Is it suppose to *modify `integers` in-place*? – juanpa.arrivillaga Nov 14 '17 at 22:16
  • Code usually executes super fast - far beyond what a human can perceive. Even if you were to manually iterate through the list, it would probably still be fast enough for your purposes. – Gry- Nov 14 '17 at 22:19
  • @juanpa.arrivillaga it's not finished yet but is suppose to find the smallest iteration of a number in a list. (with the fewest occurences) but at the highest index. – SamCramphorn Nov 14 '17 at 22:20
  • Does this answer your question? [Remove all occurrences of a value from a list?](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – Georgy Feb 19 '20 at 15:20

2 Answers2

5

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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • This worked - will mark as correct when the time is up. (22:29) Can you explain what this does exactly? Does it just rebuild the list and skips the number which isn't 1? :) – SamCramphorn Nov 14 '17 at 22:16
  • This creates a new list excluding all the `1`s and assigns it to `x`. You can also do it using a slice assignment so it will keep the same list, but change its contents. `x[:] = (i for i in x if i != 1)` – kindall Nov 14 '17 at 22:18
  • @SamCramphorn list comprehension allows you to iterate over a list and combine the conditional statement with the iteration at the end. In this case, it takes each value in `x` and checks if it is equal to one. If it is not, then it is included in the new list `x`. – Ajax1234 Nov 14 '17 at 22:20
  • BTW, the one caveat is that this does not mutate the original list object but creates a new list and reassigns the variable. If you want to achieve the former, use `x[:] = ...` – user2390182 Nov 14 '17 at 22:24
  • Many Thanks @Ajax1234 I'll use this in the future! – SamCramphorn Nov 14 '17 at 22:32
  • Impresive! I love one line answers! +1 – Ender Look Nov 14 '17 at 23:03
2

List Comprehension to the rescue.

x = [v for v in x if v != 1]
user9170
  • 950
  • 9
  • 18