Is there a simple way to delete a list element by value?












811















a=[1,2,3,4]
b=a.index(6)
del a[b]
print a


The above shows the following error:



Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list


So I have to do this:



a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
pass
print a


But is there not a simpler way to do this?










share|improve this question




















  • 14





    You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

    – Johannes Charra
    May 8 '10 at 7:51






  • 4





    this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

    – Dave Kirby
    May 8 '10 at 7:57






  • 50





    @Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

    – ibz
    Aug 15 '11 at 8:34
















811















a=[1,2,3,4]
b=a.index(6)
del a[b]
print a


The above shows the following error:



Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list


So I have to do this:



a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
pass
print a


But is there not a simpler way to do this?










share|improve this question




















  • 14





    You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

    – Johannes Charra
    May 8 '10 at 7:51






  • 4





    this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

    – Dave Kirby
    May 8 '10 at 7:57






  • 50





    @Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

    – ibz
    Aug 15 '11 at 8:34














811












811








811


152






a=[1,2,3,4]
b=a.index(6)
del a[b]
print a


The above shows the following error:



Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list


So I have to do this:



a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
pass
print a


But is there not a simpler way to do this?










share|improve this question
















a=[1,2,3,4]
b=a.index(6)
del a[b]
print a


The above shows the following error:



Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b=a.index(6)
ValueError: list.index(x): x not in list


So I have to do this:



a=[1,2,3,4]
try:
b=a.index(6)
del a[b]
except:
pass
print a


But is there not a simpler way to do this?







python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 20 '17 at 22:16









martineau

70k1092186




70k1092186










asked May 8 '10 at 7:48









zjm1126zjm1126

19.2k61149205




19.2k61149205








  • 14





    You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

    – Johannes Charra
    May 8 '10 at 7:51






  • 4





    this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

    – Dave Kirby
    May 8 '10 at 7:57






  • 50





    @Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

    – ibz
    Aug 15 '11 at 8:34














  • 14





    You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

    – Johannes Charra
    May 8 '10 at 7:51






  • 4





    this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

    – Dave Kirby
    May 8 '10 at 7:57






  • 50





    @Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

    – ibz
    Aug 15 '11 at 8:34








14




14





You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

– Johannes Charra
May 8 '10 at 7:51





You calculate the index of 6 in your list. But 6 is not in your list ... so what's supposed to happen? :)

– Johannes Charra
May 8 '10 at 7:51




4




4





this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

– Dave Kirby
May 8 '10 at 7:57





this has nothing to do with deleting a value in a list, since your code does not reach the del statement. Maybe you should retitle it "how do I get the index of a value that is not in a list. Obvious answer - you can't.

– Dave Kirby
May 8 '10 at 7:57




50




50





@Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

– ibz
Aug 15 '11 at 8:34





@Dave Well, not really. He wants to delete an item from the list regardless of whether it exists or not, not to get the index for a nonexistent item. The question is well asked.

– ibz
Aug 15 '11 at 8:34












21 Answers
21






active

oldest

votes


















1345














To remove an element's first occurrence in a list, simply use list.remove:



>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']


Mind that it does not remove all occurrences of your element. Use a list comprehension for that.



>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print a
[10, 30, 40, 30, 40, 70]





share|improve this answer





















  • 129





    Fails if the element is not in the list. :)

    – ibz
    Aug 15 '11 at 8:36






  • 19





    @ibz list comprehension does not fail even if the element isn't in the list, does it?

    – IsaacS
    Apr 26 '13 at 4:10






  • 71





    To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

    – Casey Falk
    Jul 4 '14 at 17:50






  • 3





    ++ for comment, that #2 is not the position! Missed that the first few times.

    – DarthCaniac
    Oct 21 '14 at 19:54






  • 7





    The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

    – Sebastien
    Nov 26 '15 at 16:16



















161














Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:



if c in a:
a.remove(c)


or:



try:
a.remove(c)
except ValueError:
pass


An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.






share|improve this answer



















  • 8





    Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

    – Gusdor
    Feb 9 '13 at 16:11






  • 72





    Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

    – Dave Webb
    Feb 12 '13 at 8:25






  • 5





    @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

    – jfs
    Sep 21 '13 at 11:16






  • 5





    @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

    – Gusdor
    Sep 21 '13 at 18:58






  • 2





    @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

    – Jeet
    Oct 15 '14 at 4:44



















73














You can do



a=[1,2,3,4]
if 6 in a:
a.remove(6)


but above need to search 6 in list a 2 times, so try except would be faster



try:
a.remove(6)
except:
pass





share|improve this answer



















  • 13





    Excellent. You explained why the second option is the best. Thank you.

    – Gaston Sanchez
    Nov 15 '13 at 6:38





















49














Consider:



a = [1,2,2,3,4,5]


To take out all occurrences, you could use the filter function in python.
For example, it would look like:



a = list(filter(lambda x: x!= 2, a))


So, it would keep all elements of a != 2.



To just take out one of the items use



a.remove(2)





share|improve this answer


























  • Why do you wrap filter() in another list()? According to the manual, it already returns a list.

    – Olaf Dietsche
    Oct 10 '15 at 14:11






  • 7





    @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

    – mathwizurd
    Oct 10 '15 at 16:27











  • Thank you for this explanation. I didn't look at Python 3.

    – Olaf Dietsche
    Oct 10 '15 at 17:00



















13














Here's how to do it inplace (without list comprehension):



def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]





share|improve this answer
























  • Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

    – Larold
    Aug 22 '14 at 17:34













  • @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

    – jfs
    Aug 23 '14 at 2:44



















11














If you know what value to delete, here's a simple way (as simple as I can think of, anyway):



a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
a.remove(1)


You'll get
[0, 0, 2, 3, 4]






share|improve this answer



















  • 4





    Why not use while 1 in a: as the loop structure?

    – TerminalDilettante
    Aug 27 '15 at 12:44






  • 11





    This is O(n^2) where a comprehension would be O(n).

    – Mad Physicist
    Sep 30 '15 at 2:59






  • 1





    Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

    – gil
    Feb 6 '16 at 3:27



















11














Another possibility is to use a set instead of a list, if a set is applicable in your application.



IE if your data is not ordered, and does not have duplicates, then



my_set=set([3,4,2])
my_set.discard(1)


is error-free.



Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.



my_set.add(3)


doesn't change my_set from above.






share|improve this answer































    9














    As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:



    from contextlib import suppress
    with suppress(ValueError):
    a.remove('b')





    share|improve this answer































      7














      Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:



      >>> a = [1, 2, 3, 4]
      >>> try:
      ... a.remove(6)
      ... except ValueError:
      ... pass
      ...
      >>> print a
      [1, 2, 3, 4]
      >>> try:
      ... a.remove(3)
      ... except ValueError:
      ... pass
      ...
      >>> print a
      [1, 2, 4]


      If you do this often, you can wrap it up in a function:



      def remove_if_exists(L, value):
      try:
      L.remove(value)
      except ValueError:
      pass





      share|improve this answer































        7














        This example is fast and will delete all instances of a value from the list:



        a = [1,2,3,1,2,3,4]
        while True:
        try:
        a.remove(3)
        except:
        break
        print a
        >>> [1, 2, 1, 2, 4]





        share|improve this answer





















        • 2





          if you do this you should really only break on except ValueError.

          – Anthon
          Jul 22 '18 at 8:11



















        6














        If your elements are distinct, then a simple set difference will do.



        c = [1,2,3,4,'x',8,6,7,'x',9,'x']
        z = list(set(c) - set(['x']))
        print z
        [1, 2, 3, 4, 6, 7, 8, 9]





        share|improve this answer



















        • 2





          If your elements are distinct and you don’t care about order.

          – Tom Zych
          Aug 5 '18 at 16:38



















        4














        in one line:



        a.remove('b') if 'b' in a else None


        sometimes it usefull






        share|improve this answer































          3














          We can also use .pop:



          >>> lst = [23,34,54,45]
          >>> remove_element = 23
          >>> if remove_element in lst:
          ... lst.pop(lst.index(remove_element))
          ...
          23
          >>> lst
          [34, 54, 45]
          >>>





          share|improve this answer































            3














            Overwrite the list by indexing everything except the elements you wish to remove



            >>> s = [5,4,3,2,1]
            >>> s[0:2] + s[3:]
            [5, 4, 2, 1]





            share|improve this answer































              2














              With a for loop and a condition:



              def cleaner(seq, value):    
              temp =
              for number in seq:
              if number != value:
              temp.append(number)
              return temp


              And if you want to remove some, but not all:



              def cleaner(seq, value, occ):
              temp =
              for number in seq:
              if number == value and occ:
              occ -= 1
              continue
              else:
              temp.append(number)
              return temp





              share|improve this answer































                2














                 list1=[1,2,3,3,4,5,6,1,3,4,5]
                n=int(input('enter number'))
                while n in list1:
                list1.remove(n)
                print(list1)





                share|improve this answer


























                • It's without using filter function

                  – Ravikiran D
                  Jul 25 '17 at 3:31



















                2














                Say for example, we want to remove all 1's from x. This is how I would go about it:



                x = [1, 2, 3, 1, 2, 3]


                Now, this is a practical use of my method:



                def Function(List, Unwanted):
                [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
                return List
                x = Function(x, 1)
                print(x)


                And this is my method in a single line:



                [x.remove(1) for Item in range(x.count(1))]
                print(x)


                Both yield this as an output:



                [2, 3, 2, 3, 2, 3]


                Hope this helps.
                PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.






                share|improve this answer































                  1














                  Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.



                  In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.



                  In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it



                  Then, Im used:



                  c = len(list)-1
                  for element in (reversed(list)):
                  if condition(element):
                  del list[c]
                  c -= 1
                  print(list)


                  where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]



                  Also You can do more pythonic using enumerate:



                  for i, element in enumerate(reversed(list)):
                  if condition(element):
                  del list[(i+1)*-1]
                  print(list)





                  share|improve this answer

































                    0














                    arr = [1, 1, 3, 4, 5, 2, 4, 3]

                    # to remove first occurence of that element, suppose 3 in this example
                    arr.remove(3)

                    # to remove all occurences of that element, again suppose 3
                    # use something called list comprehension
                    new_arr = [element for element in arr if element!=3]

                    # if you want to delete a position use "pop" function, suppose
                    # position 4
                    # the pop function also returns a value
                    removed_element = arr.pop(4)

                    # u can also use "del" to delete a position
                    del arr[4]





                    share|improve this answer































                      0














                      This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:



                      while "-v" in sys.argv:
                      sys.argv.remove('-v')


                      You can see the code in action, in a file called speechToText.py:



                      $ python speechToText.py -v
                      ['speechToText.py']

                      $ python speechToText.py -x
                      ['speechToText.py', '-x']

                      $ python speechToText.py -v -v
                      ['speechToText.py']

                      $ python speechToText.py -v -v -x
                      ['speechToText.py', '-x']





                      share|improve this answer































                        -2














                        Yes. This is what I found to be most useful:



                        import sys

                        a = [1, 2, 3, 4]

                        y = 0

                        if y < 1:
                        a.remove(1)
                        print len(a)
                        else:
                        sys.exit()


                        Now .remove() only takes one argument, so you can only remove one integer from your list.






                        share|improve this answer
























                        • @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                          – ozy
                          Aug 28 '15 at 20:05






                        • 6





                          The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                          – John Coleman
                          Aug 28 '15 at 20:16












                        Your Answer






                        StackExchange.ifUsing("editor", function () {
                        StackExchange.using("externalEditor", function () {
                        StackExchange.using("snippets", function () {
                        StackExchange.snippets.init();
                        });
                        });
                        }, "code-snippets");

                        StackExchange.ready(function() {
                        var channelOptions = {
                        tags: "".split(" "),
                        id: "1"
                        };
                        initTagRenderer("".split(" "), "".split(" "), channelOptions);

                        StackExchange.using("externalEditor", function() {
                        // Have to fire editor after snippets, if snippets enabled
                        if (StackExchange.settings.snippets.snippetsEnabled) {
                        StackExchange.using("snippets", function() {
                        createEditor();
                        });
                        }
                        else {
                        createEditor();
                        }
                        });

                        function createEditor() {
                        StackExchange.prepareEditor({
                        heartbeatType: 'answer',
                        autoActivateHeartbeat: false,
                        convertImagesToLinks: true,
                        noModals: true,
                        showLowRepImageUploadWarning: true,
                        reputationToPostImages: 10,
                        bindNavPrevention: true,
                        postfix: "",
                        imageUploader: {
                        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                        allowUrls: true
                        },
                        onDemand: true,
                        discardSelector: ".discard-answer"
                        ,immediatelyShowMarkdownHelp:true
                        });


                        }
                        });














                        draft saved

                        draft discarded


















                        StackExchange.ready(
                        function () {
                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2793324%2fis-there-a-simple-way-to-delete-a-list-element-by-value%23new-answer', 'question_page');
                        }
                        );

                        Post as a guest















                        Required, but never shown

























                        21 Answers
                        21






                        active

                        oldest

                        votes








                        21 Answers
                        21






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes









                        1345














                        To remove an element's first occurrence in a list, simply use list.remove:



                        >>> a = ['a', 'b', 'c', 'd']
                        >>> a.remove('b')
                        >>> print a
                        ['a', 'c', 'd']


                        Mind that it does not remove all occurrences of your element. Use a list comprehension for that.



                        >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
                        >>> a = [x for x in a if x != 20]
                        >>> print a
                        [10, 30, 40, 30, 40, 70]





                        share|improve this answer





















                        • 129





                          Fails if the element is not in the list. :)

                          – ibz
                          Aug 15 '11 at 8:36






                        • 19





                          @ibz list comprehension does not fail even if the element isn't in the list, does it?

                          – IsaacS
                          Apr 26 '13 at 4:10






                        • 71





                          To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                          – Casey Falk
                          Jul 4 '14 at 17:50






                        • 3





                          ++ for comment, that #2 is not the position! Missed that the first few times.

                          – DarthCaniac
                          Oct 21 '14 at 19:54






                        • 7





                          The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                          – Sebastien
                          Nov 26 '15 at 16:16
















                        1345














                        To remove an element's first occurrence in a list, simply use list.remove:



                        >>> a = ['a', 'b', 'c', 'd']
                        >>> a.remove('b')
                        >>> print a
                        ['a', 'c', 'd']


                        Mind that it does not remove all occurrences of your element. Use a list comprehension for that.



                        >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
                        >>> a = [x for x in a if x != 20]
                        >>> print a
                        [10, 30, 40, 30, 40, 70]





                        share|improve this answer





















                        • 129





                          Fails if the element is not in the list. :)

                          – ibz
                          Aug 15 '11 at 8:36






                        • 19





                          @ibz list comprehension does not fail even if the element isn't in the list, does it?

                          – IsaacS
                          Apr 26 '13 at 4:10






                        • 71





                          To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                          – Casey Falk
                          Jul 4 '14 at 17:50






                        • 3





                          ++ for comment, that #2 is not the position! Missed that the first few times.

                          – DarthCaniac
                          Oct 21 '14 at 19:54






                        • 7





                          The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                          – Sebastien
                          Nov 26 '15 at 16:16














                        1345












                        1345








                        1345







                        To remove an element's first occurrence in a list, simply use list.remove:



                        >>> a = ['a', 'b', 'c', 'd']
                        >>> a.remove('b')
                        >>> print a
                        ['a', 'c', 'd']


                        Mind that it does not remove all occurrences of your element. Use a list comprehension for that.



                        >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
                        >>> a = [x for x in a if x != 20]
                        >>> print a
                        [10, 30, 40, 30, 40, 70]





                        share|improve this answer















                        To remove an element's first occurrence in a list, simply use list.remove:



                        >>> a = ['a', 'b', 'c', 'd']
                        >>> a.remove('b')
                        >>> print a
                        ['a', 'c', 'd']


                        Mind that it does not remove all occurrences of your element. Use a list comprehension for that.



                        >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
                        >>> a = [x for x in a if x != 20]
                        >>> print a
                        [10, 30, 40, 30, 40, 70]






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jan 29 '18 at 13:54









                        ndemou

                        1,90412023




                        1,90412023










                        answered May 8 '10 at 7:56









                        Johannes CharraJohannes Charra

                        21.6k53445




                        21.6k53445








                        • 129





                          Fails if the element is not in the list. :)

                          – ibz
                          Aug 15 '11 at 8:36






                        • 19





                          @ibz list comprehension does not fail even if the element isn't in the list, does it?

                          – IsaacS
                          Apr 26 '13 at 4:10






                        • 71





                          To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                          – Casey Falk
                          Jul 4 '14 at 17:50






                        • 3





                          ++ for comment, that #2 is not the position! Missed that the first few times.

                          – DarthCaniac
                          Oct 21 '14 at 19:54






                        • 7





                          The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                          – Sebastien
                          Nov 26 '15 at 16:16














                        • 129





                          Fails if the element is not in the list. :)

                          – ibz
                          Aug 15 '11 at 8:36






                        • 19





                          @ibz list comprehension does not fail even if the element isn't in the list, does it?

                          – IsaacS
                          Apr 26 '13 at 4:10






                        • 71





                          To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                          – Casey Falk
                          Jul 4 '14 at 17:50






                        • 3





                          ++ for comment, that #2 is not the position! Missed that the first few times.

                          – DarthCaniac
                          Oct 21 '14 at 19:54






                        • 7





                          The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                          – Sebastien
                          Nov 26 '15 at 16:16








                        129




                        129





                        Fails if the element is not in the list. :)

                        – ibz
                        Aug 15 '11 at 8:36





                        Fails if the element is not in the list. :)

                        – ibz
                        Aug 15 '11 at 8:36




                        19




                        19





                        @ibz list comprehension does not fail even if the element isn't in the list, does it?

                        – IsaacS
                        Apr 26 '13 at 4:10





                        @ibz list comprehension does not fail even if the element isn't in the list, does it?

                        – IsaacS
                        Apr 26 '13 at 4:10




                        71




                        71





                        To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                        – Casey Falk
                        Jul 4 '14 at 17:50





                        To clarify for anyone skimming, it "fails" in the sense that it raises a ValueError exception.

                        – Casey Falk
                        Jul 4 '14 at 17:50




                        3




                        3





                        ++ for comment, that #2 is not the position! Missed that the first few times.

                        – DarthCaniac
                        Oct 21 '14 at 19:54





                        ++ for comment, that #2 is not the position! Missed that the first few times.

                        – DarthCaniac
                        Oct 21 '14 at 19:54




                        7




                        7





                        The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                        – Sebastien
                        Nov 26 '15 at 16:16





                        The list comprehension change the list reference so if there is a copy of the reference somewhere, the removal will not follow.

                        – Sebastien
                        Nov 26 '15 at 16:16













                        161














                        Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:



                        if c in a:
                        a.remove(c)


                        or:



                        try:
                        a.remove(c)
                        except ValueError:
                        pass


                        An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.






                        share|improve this answer



















                        • 8





                          Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                          – Gusdor
                          Feb 9 '13 at 16:11






                        • 72





                          Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                          – Dave Webb
                          Feb 12 '13 at 8:25






                        • 5





                          @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                          – jfs
                          Sep 21 '13 at 11:16






                        • 5





                          @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                          – Gusdor
                          Sep 21 '13 at 18:58






                        • 2





                          @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                          – Jeet
                          Oct 15 '14 at 4:44
















                        161














                        Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:



                        if c in a:
                        a.remove(c)


                        or:



                        try:
                        a.remove(c)
                        except ValueError:
                        pass


                        An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.






                        share|improve this answer



















                        • 8





                          Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                          – Gusdor
                          Feb 9 '13 at 16:11






                        • 72





                          Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                          – Dave Webb
                          Feb 12 '13 at 8:25






                        • 5





                          @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                          – jfs
                          Sep 21 '13 at 11:16






                        • 5





                          @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                          – Gusdor
                          Sep 21 '13 at 18:58






                        • 2





                          @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                          – Jeet
                          Oct 15 '14 at 4:44














                        161












                        161








                        161







                        Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:



                        if c in a:
                        a.remove(c)


                        or:



                        try:
                        a.remove(c)
                        except ValueError:
                        pass


                        An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.






                        share|improve this answer













                        Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:



                        if c in a:
                        a.remove(c)


                        or:



                        try:
                        a.remove(c)
                        except ValueError:
                        pass


                        An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 8 '10 at 8:02









                        Dave WebbDave Webb

                        157k49282291




                        157k49282291








                        • 8





                          Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                          – Gusdor
                          Feb 9 '13 at 16:11






                        • 72





                          Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                          – Dave Webb
                          Feb 12 '13 at 8:25






                        • 5





                          @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                          – jfs
                          Sep 21 '13 at 11:16






                        • 5





                          @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                          – Gusdor
                          Sep 21 '13 at 18:58






                        • 2





                          @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                          – Jeet
                          Oct 15 '14 at 4:44














                        • 8





                          Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                          – Gusdor
                          Feb 9 '13 at 16:11






                        • 72





                          Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                          – Dave Webb
                          Feb 12 '13 at 8:25






                        • 5





                          @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                          – jfs
                          Sep 21 '13 at 11:16






                        • 5





                          @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                          – Gusdor
                          Sep 21 '13 at 18:58






                        • 2





                          @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                          – Jeet
                          Oct 15 '14 at 4:44








                        8




                        8





                        Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                        – Gusdor
                        Feb 9 '13 at 16:11





                        Prevention is better than cure. If you can check for exceptional conditions first (example a), you should.

                        – Gusdor
                        Feb 9 '13 at 16:11




                        72




                        72





                        Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                        – Dave Webb
                        Feb 12 '13 at 8:25





                        Whilst this is true in other languages, in Python it is "easier to ask for forgiveness than permission." docs.python.org/2/glossary.html#term-eafp

                        – Dave Webb
                        Feb 12 '13 at 8:25




                        5




                        5





                        @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                        – jfs
                        Sep 21 '13 at 11:16





                        @Gusdor: if the list is shared between threads then a.remove(c) might fail anyway despite the if c in a check (a could be modified in another thread after the c in a check but before the a.remove(c) call). try/except or locks could be used to avoid the race condition.

                        – jfs
                        Sep 21 '13 at 11:16




                        5




                        5





                        @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                        – Gusdor
                        Sep 21 '13 at 18:58





                        @J.F.Sebastian if a list is shared between threads and you are not applying critical sections then you have bigger problems.

                        – Gusdor
                        Sep 21 '13 at 18:58




                        2




                        2





                        @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                        – Jeet
                        Oct 15 '14 at 4:44





                        @Gusdor, the Pythonique idiom is to try without checking and catch the exception if it occurs. It is more efficient (only one lookup instead of two), albeit a little uglier

                        – Jeet
                        Oct 15 '14 at 4:44











                        73














                        You can do



                        a=[1,2,3,4]
                        if 6 in a:
                        a.remove(6)


                        but above need to search 6 in list a 2 times, so try except would be faster



                        try:
                        a.remove(6)
                        except:
                        pass





                        share|improve this answer



















                        • 13





                          Excellent. You explained why the second option is the best. Thank you.

                          – Gaston Sanchez
                          Nov 15 '13 at 6:38


















                        73














                        You can do



                        a=[1,2,3,4]
                        if 6 in a:
                        a.remove(6)


                        but above need to search 6 in list a 2 times, so try except would be faster



                        try:
                        a.remove(6)
                        except:
                        pass





                        share|improve this answer



















                        • 13





                          Excellent. You explained why the second option is the best. Thank you.

                          – Gaston Sanchez
                          Nov 15 '13 at 6:38
















                        73












                        73








                        73







                        You can do



                        a=[1,2,3,4]
                        if 6 in a:
                        a.remove(6)


                        but above need to search 6 in list a 2 times, so try except would be faster



                        try:
                        a.remove(6)
                        except:
                        pass





                        share|improve this answer













                        You can do



                        a=[1,2,3,4]
                        if 6 in a:
                        a.remove(6)


                        but above need to search 6 in list a 2 times, so try except would be faster



                        try:
                        a.remove(6)
                        except:
                        pass






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 8 '10 at 7:57









                        YOUYOU

                        86.6k21154199




                        86.6k21154199








                        • 13





                          Excellent. You explained why the second option is the best. Thank you.

                          – Gaston Sanchez
                          Nov 15 '13 at 6:38
















                        • 13





                          Excellent. You explained why the second option is the best. Thank you.

                          – Gaston Sanchez
                          Nov 15 '13 at 6:38










                        13




                        13





                        Excellent. You explained why the second option is the best. Thank you.

                        – Gaston Sanchez
                        Nov 15 '13 at 6:38







                        Excellent. You explained why the second option is the best. Thank you.

                        – Gaston Sanchez
                        Nov 15 '13 at 6:38













                        49














                        Consider:



                        a = [1,2,2,3,4,5]


                        To take out all occurrences, you could use the filter function in python.
                        For example, it would look like:



                        a = list(filter(lambda x: x!= 2, a))


                        So, it would keep all elements of a != 2.



                        To just take out one of the items use



                        a.remove(2)





                        share|improve this answer


























                        • Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                          – Olaf Dietsche
                          Oct 10 '15 at 14:11






                        • 7





                          @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                          – mathwizurd
                          Oct 10 '15 at 16:27











                        • Thank you for this explanation. I didn't look at Python 3.

                          – Olaf Dietsche
                          Oct 10 '15 at 17:00
















                        49














                        Consider:



                        a = [1,2,2,3,4,5]


                        To take out all occurrences, you could use the filter function in python.
                        For example, it would look like:



                        a = list(filter(lambda x: x!= 2, a))


                        So, it would keep all elements of a != 2.



                        To just take out one of the items use



                        a.remove(2)





                        share|improve this answer


























                        • Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                          – Olaf Dietsche
                          Oct 10 '15 at 14:11






                        • 7





                          @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                          – mathwizurd
                          Oct 10 '15 at 16:27











                        • Thank you for this explanation. I didn't look at Python 3.

                          – Olaf Dietsche
                          Oct 10 '15 at 17:00














                        49












                        49








                        49







                        Consider:



                        a = [1,2,2,3,4,5]


                        To take out all occurrences, you could use the filter function in python.
                        For example, it would look like:



                        a = list(filter(lambda x: x!= 2, a))


                        So, it would keep all elements of a != 2.



                        To just take out one of the items use



                        a.remove(2)





                        share|improve this answer















                        Consider:



                        a = [1,2,2,3,4,5]


                        To take out all occurrences, you could use the filter function in python.
                        For example, it would look like:



                        a = list(filter(lambda x: x!= 2, a))


                        So, it would keep all elements of a != 2.



                        To just take out one of the items use



                        a.remove(2)






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 16 '14 at 1:59

























                        answered Aug 11 '14 at 19:55









                        mathwizurdmathwizurd

                        897812




                        897812













                        • Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                          – Olaf Dietsche
                          Oct 10 '15 at 14:11






                        • 7





                          @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                          – mathwizurd
                          Oct 10 '15 at 16:27











                        • Thank you for this explanation. I didn't look at Python 3.

                          – Olaf Dietsche
                          Oct 10 '15 at 17:00



















                        • Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                          – Olaf Dietsche
                          Oct 10 '15 at 14:11






                        • 7





                          @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                          – mathwizurd
                          Oct 10 '15 at 16:27











                        • Thank you for this explanation. I didn't look at Python 3.

                          – Olaf Dietsche
                          Oct 10 '15 at 17:00

















                        Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                        – Olaf Dietsche
                        Oct 10 '15 at 14:11





                        Why do you wrap filter() in another list()? According to the manual, it already returns a list.

                        – Olaf Dietsche
                        Oct 10 '15 at 14:11




                        7




                        7





                        @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                        – mathwizurd
                        Oct 10 '15 at 16:27





                        @OlafDietsche In Python 3.x, it returns a filter object (in 2.x, it returns a list), so I have to cast "a" to a list for it to have any functionality.

                        – mathwizurd
                        Oct 10 '15 at 16:27













                        Thank you for this explanation. I didn't look at Python 3.

                        – Olaf Dietsche
                        Oct 10 '15 at 17:00





                        Thank you for this explanation. I didn't look at Python 3.

                        – Olaf Dietsche
                        Oct 10 '15 at 17:00











                        13














                        Here's how to do it inplace (without list comprehension):



                        def remove_all(seq, value):
                        pos = 0
                        for item in seq:
                        if item != value:
                        seq[pos] = item
                        pos += 1
                        del seq[pos:]





                        share|improve this answer
























                        • Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                          – Larold
                          Aug 22 '14 at 17:34













                        • @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                          – jfs
                          Aug 23 '14 at 2:44
















                        13














                        Here's how to do it inplace (without list comprehension):



                        def remove_all(seq, value):
                        pos = 0
                        for item in seq:
                        if item != value:
                        seq[pos] = item
                        pos += 1
                        del seq[pos:]





                        share|improve this answer
























                        • Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                          – Larold
                          Aug 22 '14 at 17:34













                        • @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                          – jfs
                          Aug 23 '14 at 2:44














                        13












                        13








                        13







                        Here's how to do it inplace (without list comprehension):



                        def remove_all(seq, value):
                        pos = 0
                        for item in seq:
                        if item != value:
                        seq[pos] = item
                        pos += 1
                        del seq[pos:]





                        share|improve this answer













                        Here's how to do it inplace (without list comprehension):



                        def remove_all(seq, value):
                        pos = 0
                        for item in seq:
                        if item != value:
                        seq[pos] = item
                        pos += 1
                        del seq[pos:]






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 8 '10 at 14:57









                        jfsjfs

                        271k815731128




                        271k815731128













                        • Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                          – Larold
                          Aug 22 '14 at 17:34













                        • @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                          – jfs
                          Aug 23 '14 at 2:44



















                        • Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                          – Larold
                          Aug 22 '14 at 17:34













                        • @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                          – jfs
                          Aug 23 '14 at 2:44

















                        Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                        – Larold
                        Aug 22 '14 at 17:34







                        Very clever - I really like this - unfortunately it seems to be as inefficient as the most popular answer. gil's solution is actually much faster for giant lists with only a few occurrences of the value you wish to remove.

                        – Larold
                        Aug 22 '14 at 17:34















                        @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                        – jfs
                        Aug 23 '14 at 2:44





                        @Larold The fastest way would be a separate question. My money are on list comprehension in the general case. This solution should perform really well if the value is frequent in the input list and list comprehension is not used. Try Pypy, numpy data in Cython. [@Gill's answer is O(n*n) unnecessarily (compare 1e6 and 1e12 – you don't want to risk the latter). while 1: L.remove(value) and return on ValueError might work well with a few values or small lists in CPython.

                        – jfs
                        Aug 23 '14 at 2:44











                        11














                        If you know what value to delete, here's a simple way (as simple as I can think of, anyway):



                        a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
                        while a.count(1) > 0:
                        a.remove(1)


                        You'll get
                        [0, 0, 2, 3, 4]






                        share|improve this answer



















                        • 4





                          Why not use while 1 in a: as the loop structure?

                          – TerminalDilettante
                          Aug 27 '15 at 12:44






                        • 11





                          This is O(n^2) where a comprehension would be O(n).

                          – Mad Physicist
                          Sep 30 '15 at 2:59






                        • 1





                          Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                          – gil
                          Feb 6 '16 at 3:27
















                        11














                        If you know what value to delete, here's a simple way (as simple as I can think of, anyway):



                        a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
                        while a.count(1) > 0:
                        a.remove(1)


                        You'll get
                        [0, 0, 2, 3, 4]






                        share|improve this answer



















                        • 4





                          Why not use while 1 in a: as the loop structure?

                          – TerminalDilettante
                          Aug 27 '15 at 12:44






                        • 11





                          This is O(n^2) where a comprehension would be O(n).

                          – Mad Physicist
                          Sep 30 '15 at 2:59






                        • 1





                          Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                          – gil
                          Feb 6 '16 at 3:27














                        11












                        11








                        11







                        If you know what value to delete, here's a simple way (as simple as I can think of, anyway):



                        a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
                        while a.count(1) > 0:
                        a.remove(1)


                        You'll get
                        [0, 0, 2, 3, 4]






                        share|improve this answer













                        If you know what value to delete, here's a simple way (as simple as I can think of, anyway):



                        a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
                        while a.count(1) > 0:
                        a.remove(1)


                        You'll get
                        [0, 0, 2, 3, 4]







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 28 '13 at 21:20









                        gilgil

                        1,618812




                        1,618812








                        • 4





                          Why not use while 1 in a: as the loop structure?

                          – TerminalDilettante
                          Aug 27 '15 at 12:44






                        • 11





                          This is O(n^2) where a comprehension would be O(n).

                          – Mad Physicist
                          Sep 30 '15 at 2:59






                        • 1





                          Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                          – gil
                          Feb 6 '16 at 3:27














                        • 4





                          Why not use while 1 in a: as the loop structure?

                          – TerminalDilettante
                          Aug 27 '15 at 12:44






                        • 11





                          This is O(n^2) where a comprehension would be O(n).

                          – Mad Physicist
                          Sep 30 '15 at 2:59






                        • 1





                          Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                          – gil
                          Feb 6 '16 at 3:27








                        4




                        4





                        Why not use while 1 in a: as the loop structure?

                        – TerminalDilettante
                        Aug 27 '15 at 12:44





                        Why not use while 1 in a: as the loop structure?

                        – TerminalDilettante
                        Aug 27 '15 at 12:44




                        11




                        11





                        This is O(n^2) where a comprehension would be O(n).

                        – Mad Physicist
                        Sep 30 '15 at 2:59





                        This is O(n^2) where a comprehension would be O(n).

                        – Mad Physicist
                        Sep 30 '15 at 2:59




                        1




                        1





                        Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                        – gil
                        Feb 6 '16 at 3:27





                        Of course @MadPhysicist is right, and TerminalDilettante's version is a lot more pythonic, even if we don't care about performance. 2013 was I just began to learn Python and nowadays I'm quite often ashamed of what I wrote back then.

                        – gil
                        Feb 6 '16 at 3:27











                        11














                        Another possibility is to use a set instead of a list, if a set is applicable in your application.



                        IE if your data is not ordered, and does not have duplicates, then



                        my_set=set([3,4,2])
                        my_set.discard(1)


                        is error-free.



                        Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.



                        my_set.add(3)


                        doesn't change my_set from above.






                        share|improve this answer




























                          11














                          Another possibility is to use a set instead of a list, if a set is applicable in your application.



                          IE if your data is not ordered, and does not have duplicates, then



                          my_set=set([3,4,2])
                          my_set.discard(1)


                          is error-free.



                          Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.



                          my_set.add(3)


                          doesn't change my_set from above.






                          share|improve this answer


























                            11












                            11








                            11







                            Another possibility is to use a set instead of a list, if a set is applicable in your application.



                            IE if your data is not ordered, and does not have duplicates, then



                            my_set=set([3,4,2])
                            my_set.discard(1)


                            is error-free.



                            Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.



                            my_set.add(3)


                            doesn't change my_set from above.






                            share|improve this answer













                            Another possibility is to use a set instead of a list, if a set is applicable in your application.



                            IE if your data is not ordered, and does not have duplicates, then



                            my_set=set([3,4,2])
                            my_set.discard(1)


                            is error-free.



                            Often a list is just a handy container for items that are actually unordered. There are questions asking how to remove all occurences of an element from a list. If you don't want dupes in the first place, once again a set is handy.



                            my_set.add(3)


                            doesn't change my_set from above.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 1 '16 at 23:13









                            GreenAsJadeGreenAsJade

                            11.6k94678




                            11.6k94678























                                9














                                As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:



                                from contextlib import suppress
                                with suppress(ValueError):
                                a.remove('b')





                                share|improve this answer




























                                  9














                                  As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:



                                  from contextlib import suppress
                                  with suppress(ValueError):
                                  a.remove('b')





                                  share|improve this answer


























                                    9












                                    9








                                    9







                                    As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:



                                    from contextlib import suppress
                                    with suppress(ValueError):
                                    a.remove('b')





                                    share|improve this answer













                                    As stated by numerous other answers, list.remove() will work, but throw a ValueError if the item wasn't in the list. With python 3.4+, there's an interesting approach to handling this, using the suppress contextmanager:



                                    from contextlib import suppress
                                    with suppress(ValueError):
                                    a.remove('b')






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Sep 19 '17 at 11:36









                                    FelkFelk

                                    4,4871737




                                    4,4871737























                                        7














                                        Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:



                                        >>> a = [1, 2, 3, 4]
                                        >>> try:
                                        ... a.remove(6)
                                        ... except ValueError:
                                        ... pass
                                        ...
                                        >>> print a
                                        [1, 2, 3, 4]
                                        >>> try:
                                        ... a.remove(3)
                                        ... except ValueError:
                                        ... pass
                                        ...
                                        >>> print a
                                        [1, 2, 4]


                                        If you do this often, you can wrap it up in a function:



                                        def remove_if_exists(L, value):
                                        try:
                                        L.remove(value)
                                        except ValueError:
                                        pass





                                        share|improve this answer




























                                          7














                                          Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:



                                          >>> a = [1, 2, 3, 4]
                                          >>> try:
                                          ... a.remove(6)
                                          ... except ValueError:
                                          ... pass
                                          ...
                                          >>> print a
                                          [1, 2, 3, 4]
                                          >>> try:
                                          ... a.remove(3)
                                          ... except ValueError:
                                          ... pass
                                          ...
                                          >>> print a
                                          [1, 2, 4]


                                          If you do this often, you can wrap it up in a function:



                                          def remove_if_exists(L, value):
                                          try:
                                          L.remove(value)
                                          except ValueError:
                                          pass





                                          share|improve this answer


























                                            7












                                            7








                                            7







                                            Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:



                                            >>> a = [1, 2, 3, 4]
                                            >>> try:
                                            ... a.remove(6)
                                            ... except ValueError:
                                            ... pass
                                            ...
                                            >>> print a
                                            [1, 2, 3, 4]
                                            >>> try:
                                            ... a.remove(3)
                                            ... except ValueError:
                                            ... pass
                                            ...
                                            >>> print a
                                            [1, 2, 4]


                                            If you do this often, you can wrap it up in a function:



                                            def remove_if_exists(L, value):
                                            try:
                                            L.remove(value)
                                            except ValueError:
                                            pass





                                            share|improve this answer













                                            Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:



                                            >>> a = [1, 2, 3, 4]
                                            >>> try:
                                            ... a.remove(6)
                                            ... except ValueError:
                                            ... pass
                                            ...
                                            >>> print a
                                            [1, 2, 3, 4]
                                            >>> try:
                                            ... a.remove(3)
                                            ... except ValueError:
                                            ... pass
                                            ...
                                            >>> print a
                                            [1, 2, 4]


                                            If you do this often, you can wrap it up in a function:



                                            def remove_if_exists(L, value):
                                            try:
                                            L.remove(value)
                                            except ValueError:
                                            pass






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered May 8 '10 at 7:58







                                            Roger Pate






























                                                7














                                                This example is fast and will delete all instances of a value from the list:



                                                a = [1,2,3,1,2,3,4]
                                                while True:
                                                try:
                                                a.remove(3)
                                                except:
                                                break
                                                print a
                                                >>> [1, 2, 1, 2, 4]





                                                share|improve this answer





















                                                • 2





                                                  if you do this you should really only break on except ValueError.

                                                  – Anthon
                                                  Jul 22 '18 at 8:11
















                                                7














                                                This example is fast and will delete all instances of a value from the list:



                                                a = [1,2,3,1,2,3,4]
                                                while True:
                                                try:
                                                a.remove(3)
                                                except:
                                                break
                                                print a
                                                >>> [1, 2, 1, 2, 4]





                                                share|improve this answer





















                                                • 2





                                                  if you do this you should really only break on except ValueError.

                                                  – Anthon
                                                  Jul 22 '18 at 8:11














                                                7












                                                7








                                                7







                                                This example is fast and will delete all instances of a value from the list:



                                                a = [1,2,3,1,2,3,4]
                                                while True:
                                                try:
                                                a.remove(3)
                                                except:
                                                break
                                                print a
                                                >>> [1, 2, 1, 2, 4]





                                                share|improve this answer















                                                This example is fast and will delete all instances of a value from the list:



                                                a = [1,2,3,1,2,3,4]
                                                while True:
                                                try:
                                                a.remove(3)
                                                except:
                                                break
                                                print a
                                                >>> [1, 2, 1, 2, 4]






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Aug 31 '15 at 2:31

























                                                answered Aug 30 '15 at 15:43









                                                Chase AdamsChase Adams

                                                39526




                                                39526








                                                • 2





                                                  if you do this you should really only break on except ValueError.

                                                  – Anthon
                                                  Jul 22 '18 at 8:11














                                                • 2





                                                  if you do this you should really only break on except ValueError.

                                                  – Anthon
                                                  Jul 22 '18 at 8:11








                                                2




                                                2





                                                if you do this you should really only break on except ValueError.

                                                – Anthon
                                                Jul 22 '18 at 8:11





                                                if you do this you should really only break on except ValueError.

                                                – Anthon
                                                Jul 22 '18 at 8:11











                                                6














                                                If your elements are distinct, then a simple set difference will do.



                                                c = [1,2,3,4,'x',8,6,7,'x',9,'x']
                                                z = list(set(c) - set(['x']))
                                                print z
                                                [1, 2, 3, 4, 6, 7, 8, 9]





                                                share|improve this answer



















                                                • 2





                                                  If your elements are distinct and you don’t care about order.

                                                  – Tom Zych
                                                  Aug 5 '18 at 16:38
















                                                6














                                                If your elements are distinct, then a simple set difference will do.



                                                c = [1,2,3,4,'x',8,6,7,'x',9,'x']
                                                z = list(set(c) - set(['x']))
                                                print z
                                                [1, 2, 3, 4, 6, 7, 8, 9]





                                                share|improve this answer



















                                                • 2





                                                  If your elements are distinct and you don’t care about order.

                                                  – Tom Zych
                                                  Aug 5 '18 at 16:38














                                                6












                                                6








                                                6







                                                If your elements are distinct, then a simple set difference will do.



                                                c = [1,2,3,4,'x',8,6,7,'x',9,'x']
                                                z = list(set(c) - set(['x']))
                                                print z
                                                [1, 2, 3, 4, 6, 7, 8, 9]





                                                share|improve this answer













                                                If your elements are distinct, then a simple set difference will do.



                                                c = [1,2,3,4,'x',8,6,7,'x',9,'x']
                                                z = list(set(c) - set(['x']))
                                                print z
                                                [1, 2, 3, 4, 6, 7, 8, 9]






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 11 '16 at 14:12









                                                PagolPagol

                                                83110




                                                83110








                                                • 2





                                                  If your elements are distinct and you don’t care about order.

                                                  – Tom Zych
                                                  Aug 5 '18 at 16:38














                                                • 2





                                                  If your elements are distinct and you don’t care about order.

                                                  – Tom Zych
                                                  Aug 5 '18 at 16:38








                                                2




                                                2





                                                If your elements are distinct and you don’t care about order.

                                                – Tom Zych
                                                Aug 5 '18 at 16:38





                                                If your elements are distinct and you don’t care about order.

                                                – Tom Zych
                                                Aug 5 '18 at 16:38











                                                4














                                                in one line:



                                                a.remove('b') if 'b' in a else None


                                                sometimes it usefull






                                                share|improve this answer




























                                                  4














                                                  in one line:



                                                  a.remove('b') if 'b' in a else None


                                                  sometimes it usefull






                                                  share|improve this answer


























                                                    4












                                                    4








                                                    4







                                                    in one line:



                                                    a.remove('b') if 'b' in a else None


                                                    sometimes it usefull






                                                    share|improve this answer













                                                    in one line:



                                                    a.remove('b') if 'b' in a else None


                                                    sometimes it usefull







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Nov 23 '18 at 13:02









                                                    Andrey SuglobovAndrey Suglobov

                                                    1749




                                                    1749























                                                        3














                                                        We can also use .pop:



                                                        >>> lst = [23,34,54,45]
                                                        >>> remove_element = 23
                                                        >>> if remove_element in lst:
                                                        ... lst.pop(lst.index(remove_element))
                                                        ...
                                                        23
                                                        >>> lst
                                                        [34, 54, 45]
                                                        >>>





                                                        share|improve this answer




























                                                          3














                                                          We can also use .pop:



                                                          >>> lst = [23,34,54,45]
                                                          >>> remove_element = 23
                                                          >>> if remove_element in lst:
                                                          ... lst.pop(lst.index(remove_element))
                                                          ...
                                                          23
                                                          >>> lst
                                                          [34, 54, 45]
                                                          >>>





                                                          share|improve this answer


























                                                            3












                                                            3








                                                            3







                                                            We can also use .pop:



                                                            >>> lst = [23,34,54,45]
                                                            >>> remove_element = 23
                                                            >>> if remove_element in lst:
                                                            ... lst.pop(lst.index(remove_element))
                                                            ...
                                                            23
                                                            >>> lst
                                                            [34, 54, 45]
                                                            >>>





                                                            share|improve this answer













                                                            We can also use .pop:



                                                            >>> lst = [23,34,54,45]
                                                            >>> remove_element = 23
                                                            >>> if remove_element in lst:
                                                            ... lst.pop(lst.index(remove_element))
                                                            ...
                                                            23
                                                            >>> lst
                                                            [34, 54, 45]
                                                            >>>






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Apr 5 '17 at 11:30









                                                            SuperNovaSuperNova

                                                            6,22923423




                                                            6,22923423























                                                                3














                                                                Overwrite the list by indexing everything except the elements you wish to remove



                                                                >>> s = [5,4,3,2,1]
                                                                >>> s[0:2] + s[3:]
                                                                [5, 4, 2, 1]





                                                                share|improve this answer




























                                                                  3














                                                                  Overwrite the list by indexing everything except the elements you wish to remove



                                                                  >>> s = [5,4,3,2,1]
                                                                  >>> s[0:2] + s[3:]
                                                                  [5, 4, 2, 1]





                                                                  share|improve this answer


























                                                                    3












                                                                    3








                                                                    3







                                                                    Overwrite the list by indexing everything except the elements you wish to remove



                                                                    >>> s = [5,4,3,2,1]
                                                                    >>> s[0:2] + s[3:]
                                                                    [5, 4, 2, 1]





                                                                    share|improve this answer













                                                                    Overwrite the list by indexing everything except the elements you wish to remove



                                                                    >>> s = [5,4,3,2,1]
                                                                    >>> s[0:2] + s[3:]
                                                                    [5, 4, 2, 1]






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Apr 7 '17 at 17:26









                                                                    kilojouleskilojoules

                                                                    3,023103882




                                                                    3,023103882























                                                                        2














                                                                        With a for loop and a condition:



                                                                        def cleaner(seq, value):    
                                                                        temp =
                                                                        for number in seq:
                                                                        if number != value:
                                                                        temp.append(number)
                                                                        return temp


                                                                        And if you want to remove some, but not all:



                                                                        def cleaner(seq, value, occ):
                                                                        temp =
                                                                        for number in seq:
                                                                        if number == value and occ:
                                                                        occ -= 1
                                                                        continue
                                                                        else:
                                                                        temp.append(number)
                                                                        return temp





                                                                        share|improve this answer




























                                                                          2














                                                                          With a for loop and a condition:



                                                                          def cleaner(seq, value):    
                                                                          temp =
                                                                          for number in seq:
                                                                          if number != value:
                                                                          temp.append(number)
                                                                          return temp


                                                                          And if you want to remove some, but not all:



                                                                          def cleaner(seq, value, occ):
                                                                          temp =
                                                                          for number in seq:
                                                                          if number == value and occ:
                                                                          occ -= 1
                                                                          continue
                                                                          else:
                                                                          temp.append(number)
                                                                          return temp





                                                                          share|improve this answer


























                                                                            2












                                                                            2








                                                                            2







                                                                            With a for loop and a condition:



                                                                            def cleaner(seq, value):    
                                                                            temp =
                                                                            for number in seq:
                                                                            if number != value:
                                                                            temp.append(number)
                                                                            return temp


                                                                            And if you want to remove some, but not all:



                                                                            def cleaner(seq, value, occ):
                                                                            temp =
                                                                            for number in seq:
                                                                            if number == value and occ:
                                                                            occ -= 1
                                                                            continue
                                                                            else:
                                                                            temp.append(number)
                                                                            return temp





                                                                            share|improve this answer













                                                                            With a for loop and a condition:



                                                                            def cleaner(seq, value):    
                                                                            temp =
                                                                            for number in seq:
                                                                            if number != value:
                                                                            temp.append(number)
                                                                            return temp


                                                                            And if you want to remove some, but not all:



                                                                            def cleaner(seq, value, occ):
                                                                            temp =
                                                                            for number in seq:
                                                                            if number == value and occ:
                                                                            occ -= 1
                                                                            continue
                                                                            else:
                                                                            temp.append(number)
                                                                            return temp






                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered May 5 '17 at 21:12









                                                                            user7970984user7970984

                                                                            211




                                                                            211























                                                                                2














                                                                                 list1=[1,2,3,3,4,5,6,1,3,4,5]
                                                                                n=int(input('enter number'))
                                                                                while n in list1:
                                                                                list1.remove(n)
                                                                                print(list1)





                                                                                share|improve this answer


























                                                                                • It's without using filter function

                                                                                  – Ravikiran D
                                                                                  Jul 25 '17 at 3:31
















                                                                                2














                                                                                 list1=[1,2,3,3,4,5,6,1,3,4,5]
                                                                                n=int(input('enter number'))
                                                                                while n in list1:
                                                                                list1.remove(n)
                                                                                print(list1)





                                                                                share|improve this answer


























                                                                                • It's without using filter function

                                                                                  – Ravikiran D
                                                                                  Jul 25 '17 at 3:31














                                                                                2












                                                                                2








                                                                                2







                                                                                 list1=[1,2,3,3,4,5,6,1,3,4,5]
                                                                                n=int(input('enter number'))
                                                                                while n in list1:
                                                                                list1.remove(n)
                                                                                print(list1)





                                                                                share|improve this answer















                                                                                 list1=[1,2,3,3,4,5,6,1,3,4,5]
                                                                                n=int(input('enter number'))
                                                                                while n in list1:
                                                                                list1.remove(n)
                                                                                print(list1)






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Jul 25 '17 at 3:30

























                                                                                answered Jul 24 '17 at 16:54









                                                                                Ravikiran DRavikiran D

                                                                                9116




                                                                                9116













                                                                                • It's without using filter function

                                                                                  – Ravikiran D
                                                                                  Jul 25 '17 at 3:31



















                                                                                • It's without using filter function

                                                                                  – Ravikiran D
                                                                                  Jul 25 '17 at 3:31

















                                                                                It's without using filter function

                                                                                – Ravikiran D
                                                                                Jul 25 '17 at 3:31





                                                                                It's without using filter function

                                                                                – Ravikiran D
                                                                                Jul 25 '17 at 3:31











                                                                                2














                                                                                Say for example, we want to remove all 1's from x. This is how I would go about it:



                                                                                x = [1, 2, 3, 1, 2, 3]


                                                                                Now, this is a practical use of my method:



                                                                                def Function(List, Unwanted):
                                                                                [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
                                                                                return List
                                                                                x = Function(x, 1)
                                                                                print(x)


                                                                                And this is my method in a single line:



                                                                                [x.remove(1) for Item in range(x.count(1))]
                                                                                print(x)


                                                                                Both yield this as an output:



                                                                                [2, 3, 2, 3, 2, 3]


                                                                                Hope this helps.
                                                                                PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.






                                                                                share|improve this answer




























                                                                                  2














                                                                                  Say for example, we want to remove all 1's from x. This is how I would go about it:



                                                                                  x = [1, 2, 3, 1, 2, 3]


                                                                                  Now, this is a practical use of my method:



                                                                                  def Function(List, Unwanted):
                                                                                  [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
                                                                                  return List
                                                                                  x = Function(x, 1)
                                                                                  print(x)


                                                                                  And this is my method in a single line:



                                                                                  [x.remove(1) for Item in range(x.count(1))]
                                                                                  print(x)


                                                                                  Both yield this as an output:



                                                                                  [2, 3, 2, 3, 2, 3]


                                                                                  Hope this helps.
                                                                                  PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.






                                                                                  share|improve this answer


























                                                                                    2












                                                                                    2








                                                                                    2







                                                                                    Say for example, we want to remove all 1's from x. This is how I would go about it:



                                                                                    x = [1, 2, 3, 1, 2, 3]


                                                                                    Now, this is a practical use of my method:



                                                                                    def Function(List, Unwanted):
                                                                                    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
                                                                                    return List
                                                                                    x = Function(x, 1)
                                                                                    print(x)


                                                                                    And this is my method in a single line:



                                                                                    [x.remove(1) for Item in range(x.count(1))]
                                                                                    print(x)


                                                                                    Both yield this as an output:



                                                                                    [2, 3, 2, 3, 2, 3]


                                                                                    Hope this helps.
                                                                                    PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.






                                                                                    share|improve this answer













                                                                                    Say for example, we want to remove all 1's from x. This is how I would go about it:



                                                                                    x = [1, 2, 3, 1, 2, 3]


                                                                                    Now, this is a practical use of my method:



                                                                                    def Function(List, Unwanted):
                                                                                    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
                                                                                    return List
                                                                                    x = Function(x, 1)
                                                                                    print(x)


                                                                                    And this is my method in a single line:



                                                                                    [x.remove(1) for Item in range(x.count(1))]
                                                                                    print(x)


                                                                                    Both yield this as an output:



                                                                                    [2, 3, 2, 3, 2, 3]


                                                                                    Hope this helps.
                                                                                    PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Sep 19 '17 at 11:31









                                                                                    Krohnus MelaveaKrohnus Melavea

                                                                                    1077




                                                                                    1077























                                                                                        1














                                                                                        Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.



                                                                                        In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.



                                                                                        In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it



                                                                                        Then, Im used:



                                                                                        c = len(list)-1
                                                                                        for element in (reversed(list)):
                                                                                        if condition(element):
                                                                                        del list[c]
                                                                                        c -= 1
                                                                                        print(list)


                                                                                        where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]



                                                                                        Also You can do more pythonic using enumerate:



                                                                                        for i, element in enumerate(reversed(list)):
                                                                                        if condition(element):
                                                                                        del list[(i+1)*-1]
                                                                                        print(list)





                                                                                        share|improve this answer






























                                                                                          1














                                                                                          Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.



                                                                                          In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.



                                                                                          In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it



                                                                                          Then, Im used:



                                                                                          c = len(list)-1
                                                                                          for element in (reversed(list)):
                                                                                          if condition(element):
                                                                                          del list[c]
                                                                                          c -= 1
                                                                                          print(list)


                                                                                          where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]



                                                                                          Also You can do more pythonic using enumerate:



                                                                                          for i, element in enumerate(reversed(list)):
                                                                                          if condition(element):
                                                                                          del list[(i+1)*-1]
                                                                                          print(list)





                                                                                          share|improve this answer




























                                                                                            1












                                                                                            1








                                                                                            1







                                                                                            Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.



                                                                                            In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.



                                                                                            In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it



                                                                                            Then, Im used:



                                                                                            c = len(list)-1
                                                                                            for element in (reversed(list)):
                                                                                            if condition(element):
                                                                                            del list[c]
                                                                                            c -= 1
                                                                                            print(list)


                                                                                            where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]



                                                                                            Also You can do more pythonic using enumerate:



                                                                                            for i, element in enumerate(reversed(list)):
                                                                                            if condition(element):
                                                                                            del list[(i+1)*-1]
                                                                                            print(list)





                                                                                            share|improve this answer















                                                                                            Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.



                                                                                            In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.



                                                                                            In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it



                                                                                            Then, Im used:



                                                                                            c = len(list)-1
                                                                                            for element in (reversed(list)):
                                                                                            if condition(element):
                                                                                            del list[c]
                                                                                            c -= 1
                                                                                            print(list)


                                                                                            where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]



                                                                                            Also You can do more pythonic using enumerate:



                                                                                            for i, element in enumerate(reversed(list)):
                                                                                            if condition(element):
                                                                                            del list[(i+1)*-1]
                                                                                            print(list)






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Nov 23 '18 at 12:32

























                                                                                            answered Nov 23 '18 at 11:44









                                                                                            David MartínezDavid Martínez

                                                                                            213




                                                                                            213























                                                                                                0














                                                                                                arr = [1, 1, 3, 4, 5, 2, 4, 3]

                                                                                                # to remove first occurence of that element, suppose 3 in this example
                                                                                                arr.remove(3)

                                                                                                # to remove all occurences of that element, again suppose 3
                                                                                                # use something called list comprehension
                                                                                                new_arr = [element for element in arr if element!=3]

                                                                                                # if you want to delete a position use "pop" function, suppose
                                                                                                # position 4
                                                                                                # the pop function also returns a value
                                                                                                removed_element = arr.pop(4)

                                                                                                # u can also use "del" to delete a position
                                                                                                del arr[4]





                                                                                                share|improve this answer




























                                                                                                  0














                                                                                                  arr = [1, 1, 3, 4, 5, 2, 4, 3]

                                                                                                  # to remove first occurence of that element, suppose 3 in this example
                                                                                                  arr.remove(3)

                                                                                                  # to remove all occurences of that element, again suppose 3
                                                                                                  # use something called list comprehension
                                                                                                  new_arr = [element for element in arr if element!=3]

                                                                                                  # if you want to delete a position use "pop" function, suppose
                                                                                                  # position 4
                                                                                                  # the pop function also returns a value
                                                                                                  removed_element = arr.pop(4)

                                                                                                  # u can also use "del" to delete a position
                                                                                                  del arr[4]





                                                                                                  share|improve this answer


























                                                                                                    0












                                                                                                    0








                                                                                                    0







                                                                                                    arr = [1, 1, 3, 4, 5, 2, 4, 3]

                                                                                                    # to remove first occurence of that element, suppose 3 in this example
                                                                                                    arr.remove(3)

                                                                                                    # to remove all occurences of that element, again suppose 3
                                                                                                    # use something called list comprehension
                                                                                                    new_arr = [element for element in arr if element!=3]

                                                                                                    # if you want to delete a position use "pop" function, suppose
                                                                                                    # position 4
                                                                                                    # the pop function also returns a value
                                                                                                    removed_element = arr.pop(4)

                                                                                                    # u can also use "del" to delete a position
                                                                                                    del arr[4]





                                                                                                    share|improve this answer













                                                                                                    arr = [1, 1, 3, 4, 5, 2, 4, 3]

                                                                                                    # to remove first occurence of that element, suppose 3 in this example
                                                                                                    arr.remove(3)

                                                                                                    # to remove all occurences of that element, again suppose 3
                                                                                                    # use something called list comprehension
                                                                                                    new_arr = [element for element in arr if element!=3]

                                                                                                    # if you want to delete a position use "pop" function, suppose
                                                                                                    # position 4
                                                                                                    # the pop function also returns a value
                                                                                                    removed_element = arr.pop(4)

                                                                                                    # u can also use "del" to delete a position
                                                                                                    del arr[4]






                                                                                                    share|improve this answer












                                                                                                    share|improve this answer



                                                                                                    share|improve this answer










                                                                                                    answered Apr 2 '18 at 20:56









                                                                                                    Brijesh KushwahaBrijesh Kushwaha

                                                                                                    12




                                                                                                    12























                                                                                                        0














                                                                                                        This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:



                                                                                                        while "-v" in sys.argv:
                                                                                                        sys.argv.remove('-v')


                                                                                                        You can see the code in action, in a file called speechToText.py:



                                                                                                        $ python speechToText.py -v
                                                                                                        ['speechToText.py']

                                                                                                        $ python speechToText.py -x
                                                                                                        ['speechToText.py', '-x']

                                                                                                        $ python speechToText.py -v -v
                                                                                                        ['speechToText.py']

                                                                                                        $ python speechToText.py -v -v -x
                                                                                                        ['speechToText.py', '-x']





                                                                                                        share|improve this answer




























                                                                                                          0














                                                                                                          This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:



                                                                                                          while "-v" in sys.argv:
                                                                                                          sys.argv.remove('-v')


                                                                                                          You can see the code in action, in a file called speechToText.py:



                                                                                                          $ python speechToText.py -v
                                                                                                          ['speechToText.py']

                                                                                                          $ python speechToText.py -x
                                                                                                          ['speechToText.py', '-x']

                                                                                                          $ python speechToText.py -v -v
                                                                                                          ['speechToText.py']

                                                                                                          $ python speechToText.py -v -v -x
                                                                                                          ['speechToText.py', '-x']





                                                                                                          share|improve this answer


























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:



                                                                                                            while "-v" in sys.argv:
                                                                                                            sys.argv.remove('-v')


                                                                                                            You can see the code in action, in a file called speechToText.py:



                                                                                                            $ python speechToText.py -v
                                                                                                            ['speechToText.py']

                                                                                                            $ python speechToText.py -x
                                                                                                            ['speechToText.py', '-x']

                                                                                                            $ python speechToText.py -v -v
                                                                                                            ['speechToText.py']

                                                                                                            $ python speechToText.py -v -v -x
                                                                                                            ['speechToText.py', '-x']





                                                                                                            share|improve this answer













                                                                                                            This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:



                                                                                                            while "-v" in sys.argv:
                                                                                                            sys.argv.remove('-v')


                                                                                                            You can see the code in action, in a file called speechToText.py:



                                                                                                            $ python speechToText.py -v
                                                                                                            ['speechToText.py']

                                                                                                            $ python speechToText.py -x
                                                                                                            ['speechToText.py', '-x']

                                                                                                            $ python speechToText.py -v -v
                                                                                                            ['speechToText.py']

                                                                                                            $ python speechToText.py -v -v -x
                                                                                                            ['speechToText.py', '-x']






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Sep 13 '18 at 15:43









                                                                                                            Mike SlinnMike Slinn

                                                                                                            2,78142752




                                                                                                            2,78142752























                                                                                                                -2














                                                                                                                Yes. This is what I found to be most useful:



                                                                                                                import sys

                                                                                                                a = [1, 2, 3, 4]

                                                                                                                y = 0

                                                                                                                if y < 1:
                                                                                                                a.remove(1)
                                                                                                                print len(a)
                                                                                                                else:
                                                                                                                sys.exit()


                                                                                                                Now .remove() only takes one argument, so you can only remove one integer from your list.






                                                                                                                share|improve this answer
























                                                                                                                • @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                  – ozy
                                                                                                                  Aug 28 '15 at 20:05






                                                                                                                • 6





                                                                                                                  The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                  – John Coleman
                                                                                                                  Aug 28 '15 at 20:16
















                                                                                                                -2














                                                                                                                Yes. This is what I found to be most useful:



                                                                                                                import sys

                                                                                                                a = [1, 2, 3, 4]

                                                                                                                y = 0

                                                                                                                if y < 1:
                                                                                                                a.remove(1)
                                                                                                                print len(a)
                                                                                                                else:
                                                                                                                sys.exit()


                                                                                                                Now .remove() only takes one argument, so you can only remove one integer from your list.






                                                                                                                share|improve this answer
























                                                                                                                • @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                  – ozy
                                                                                                                  Aug 28 '15 at 20:05






                                                                                                                • 6





                                                                                                                  The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                  – John Coleman
                                                                                                                  Aug 28 '15 at 20:16














                                                                                                                -2












                                                                                                                -2








                                                                                                                -2







                                                                                                                Yes. This is what I found to be most useful:



                                                                                                                import sys

                                                                                                                a = [1, 2, 3, 4]

                                                                                                                y = 0

                                                                                                                if y < 1:
                                                                                                                a.remove(1)
                                                                                                                print len(a)
                                                                                                                else:
                                                                                                                sys.exit()


                                                                                                                Now .remove() only takes one argument, so you can only remove one integer from your list.






                                                                                                                share|improve this answer













                                                                                                                Yes. This is what I found to be most useful:



                                                                                                                import sys

                                                                                                                a = [1, 2, 3, 4]

                                                                                                                y = 0

                                                                                                                if y < 1:
                                                                                                                a.remove(1)
                                                                                                                print len(a)
                                                                                                                else:
                                                                                                                sys.exit()


                                                                                                                Now .remove() only takes one argument, so you can only remove one integer from your list.







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Aug 28 '15 at 19:51









                                                                                                                ozyozy

                                                                                                                44110




                                                                                                                44110













                                                                                                                • @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                  – ozy
                                                                                                                  Aug 28 '15 at 20:05






                                                                                                                • 6





                                                                                                                  The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                  – John Coleman
                                                                                                                  Aug 28 '15 at 20:16



















                                                                                                                • @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                  – ozy
                                                                                                                  Aug 28 '15 at 20:05






                                                                                                                • 6





                                                                                                                  The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                  – John Coleman
                                                                                                                  Aug 28 '15 at 20:16

















                                                                                                                @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                – ozy
                                                                                                                Aug 28 '15 at 20:05





                                                                                                                @JohnColeman I'm merely stating a solution of which the question asks. I found it "most useful" for myself, you have the right to disagree.

                                                                                                                – ozy
                                                                                                                Aug 28 '15 at 20:05




                                                                                                                6




                                                                                                                6





                                                                                                                The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                – John Coleman
                                                                                                                Aug 28 '15 at 20:16





                                                                                                                The accepted answer from years ago already mentioned remove, so you are adding nothing new there, the only new thing is that for no apparent reason you brought in sys.exit(). Furthermore, your method crashes if the target item is not in the list, and the entire point of the OP's question was how to remove elements without crashing when the method was applied to an element not in the list.

                                                                                                                – John Coleman
                                                                                                                Aug 28 '15 at 20:16


















                                                                                                                draft saved

                                                                                                                draft discarded




















































                                                                                                                Thanks for contributing an answer to Stack Overflow!


                                                                                                                • Please be sure to answer the question. Provide details and share your research!

                                                                                                                But avoid



                                                                                                                • Asking for help, clarification, or responding to other answers.

                                                                                                                • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                To learn more, see our tips on writing great answers.




                                                                                                                draft saved


                                                                                                                draft discarded














                                                                                                                StackExchange.ready(
                                                                                                                function () {
                                                                                                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2793324%2fis-there-a-simple-way-to-delete-a-list-element-by-value%23new-answer', 'question_page');
                                                                                                                }
                                                                                                                );

                                                                                                                Post as a guest















                                                                                                                Required, but never shown





















































                                                                                                                Required, but never shown














                                                                                                                Required, but never shown












                                                                                                                Required, but never shown







                                                                                                                Required, but never shown

































                                                                                                                Required, but never shown














                                                                                                                Required, but never shown












                                                                                                                Required, but never shown







                                                                                                                Required, but never shown







                                                                                                                這個網誌中的熱門文章

                                                                                                                Xamarin.form Move up view when keyboard appear

                                                                                                                Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                                                                                Anylogic : not able to use stopDelay()