How to remove list items depending on predecessor in python Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Dictionaries: How to keep keys/values in same order as declared?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to randomly select an item from a list?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?

Why not use the yoke to control yaw, as well as pitch and roll?

An isoperimetric-type inequality inside a cube

As a dual citizen, my US passport will expire one day after traveling to the US. Will this work?

Why does BitLocker not use RSA?

Statistical analysis applied to methods coming out of Machine Learning

What does 丫 mean? 丫是什么意思?

What is "Lambda" in Heston's original paper on stochastic volatility models?

How to make triangles with rounded sides and corners? (squircle with 3 sides)

Flight departed from the gate 5 min before scheduled departure time. Refund options

How do you write "wild blueberries flavored"?

Pointing to problems without suggesting solutions

How does TikZ render an arc?

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

Did pre-Columbian Americans know the spherical shape of the Earth?

3D Masyu - A Die

The Nth Gryphon Number

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Understanding piped commands in GNU/Linux

Is this Half-dragon Quaggoth boss monster balanced?

Vertical ranges of Column Plots in 12

How to name indistinguishable henchmen in a screenplay?

Does the universe have a fixed centre of mass?

In musical terms, what properties are varied by the human voice to produce different words / syllables?

Is the time—manner—place ordering of adverbials an oversimplification?



How to remove list items depending on predecessor in python



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Dictionaries: How to keep keys/values in same order as declared?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to randomly select an item from a list?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








12















Given a Python list, I want to remove consecutive 'duplicates'. The duplicate value however is a attribute of the list item (In this example, the tuple's first element).



Input:



[(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]


Desired Output:



[(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]


Cannot use set or dict, because order is important.



Cannot use list comprehension [x for x in somelist if not determine(x)], because the check depends on predecessor.



What I want is something like:



mylist = [...]

for i in range(len(mylist)):
if mylist[i-1].attr == mylist[i].attr:
mylist.remove(i)


What is the preferred way to solve this in Python?










share|improve this question



















  • 1





    Python 3.6 maintain dict order

    – Guy
    Apr 17 at 8:59











  • Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

    – Guy
    Apr 17 at 8:59






  • 3





    Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

    – Daniel Roseman
    Apr 17 at 9:00






  • 1





    What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

    – Cid
    Apr 17 at 9:01






  • 1





    @gmds You're right. Accepted and edited example accordingly.

    – Sparkofska
    Apr 17 at 9:27

















12















Given a Python list, I want to remove consecutive 'duplicates'. The duplicate value however is a attribute of the list item (In this example, the tuple's first element).



Input:



[(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]


Desired Output:



[(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]


Cannot use set or dict, because order is important.



Cannot use list comprehension [x for x in somelist if not determine(x)], because the check depends on predecessor.



What I want is something like:



mylist = [...]

for i in range(len(mylist)):
if mylist[i-1].attr == mylist[i].attr:
mylist.remove(i)


What is the preferred way to solve this in Python?










share|improve this question



















  • 1





    Python 3.6 maintain dict order

    – Guy
    Apr 17 at 8:59











  • Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

    – Guy
    Apr 17 at 8:59






  • 3





    Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

    – Daniel Roseman
    Apr 17 at 9:00






  • 1





    What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

    – Cid
    Apr 17 at 9:01






  • 1





    @gmds You're right. Accepted and edited example accordingly.

    – Sparkofska
    Apr 17 at 9:27













12












12








12


1






Given a Python list, I want to remove consecutive 'duplicates'. The duplicate value however is a attribute of the list item (In this example, the tuple's first element).



Input:



[(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]


Desired Output:



[(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]


Cannot use set or dict, because order is important.



Cannot use list comprehension [x for x in somelist if not determine(x)], because the check depends on predecessor.



What I want is something like:



mylist = [...]

for i in range(len(mylist)):
if mylist[i-1].attr == mylist[i].attr:
mylist.remove(i)


What is the preferred way to solve this in Python?










share|improve this question
















Given a Python list, I want to remove consecutive 'duplicates'. The duplicate value however is a attribute of the list item (In this example, the tuple's first element).



Input:



[(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]


Desired Output:



[(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]


Cannot use set or dict, because order is important.



Cannot use list comprehension [x for x in somelist if not determine(x)], because the check depends on predecessor.



What I want is something like:



mylist = [...]

for i in range(len(mylist)):
if mylist[i-1].attr == mylist[i].attr:
mylist.remove(i)


What is the preferred way to solve this in Python?







python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 17 at 15:26









gmds

7,121831




7,121831










asked Apr 17 at 8:57









SparkofskaSparkofska

1588




1588







  • 1





    Python 3.6 maintain dict order

    – Guy
    Apr 17 at 8:59











  • Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

    – Guy
    Apr 17 at 8:59






  • 3





    Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

    – Daniel Roseman
    Apr 17 at 9:00






  • 1





    What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

    – Cid
    Apr 17 at 9:01






  • 1





    @gmds You're right. Accepted and edited example accordingly.

    – Sparkofska
    Apr 17 at 9:27












  • 1





    Python 3.6 maintain dict order

    – Guy
    Apr 17 at 8:59











  • Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

    – Guy
    Apr 17 at 8:59






  • 3





    Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

    – Daniel Roseman
    Apr 17 at 9:00






  • 1





    What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

    – Cid
    Apr 17 at 9:01






  • 1





    @gmds You're right. Accepted and edited example accordingly.

    – Sparkofska
    Apr 17 at 9:27







1




1





Python 3.6 maintain dict order

– Guy
Apr 17 at 8:59





Python 3.6 maintain dict order

– Guy
Apr 17 at 8:59













Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

– Guy
Apr 17 at 8:59





Possible duplicate of Dictionaries: How to keep keys/values in same order as declared?

– Guy
Apr 17 at 8:59




3




3





Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

– Daniel Roseman
Apr 17 at 9:00





Are you only concerned with consecutive duplicates? That is, if the last item of the list was also 1, 'a', would that be a duplicate of the first?

– Daniel Roseman
Apr 17 at 9:00




1




1





What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

– Cid
Apr 17 at 9:01





What should be the result for [(1, 'a'), (2, 'a'), (1, 'a')] ? Should it be [(1, 'a'), (2, 'a'), (1, 'a')] or [(1, 'a'), (2, 'a')] ?

– Cid
Apr 17 at 9:01




1




1





@gmds You're right. Accepted and edited example accordingly.

– Sparkofska
Apr 17 at 9:27





@gmds You're right. Accepted and edited example accordingly.

– Sparkofska
Apr 17 at 9:27












7 Answers
7






active

oldest

votes


















13














You can use itertools.groupby (demonstration with more data):



from itertools import groupby
from operator import itemgetter

data = [(1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (3, 'a')]

[next(group) for key, group in groupby(data, key=itemgetter(0))]


Output:



[(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (2, 'a'), (3, 'a')]


For completeness, an iterative approach based on other answers:



result = []

for first, second in zip(data, data[1:]):
if first[0] != second[0]:
result.append(first)

result


Output:



[(1, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a')]


Note that this keeps the last duplicate, instead of the first.






share|improve this answer

























  • You don't need any key parameter, just take the key of each group

    – yatu
    Apr 17 at 9:05












  • @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

    – gmds
    Apr 17 at 9:06











  • I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

    – yatu
    Apr 17 at 9:09



















9














In order to remove consecutive duplicates, you could use itertools.groupby:



l = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]
from itertools import groupby
[tuple(k) for k, _ in groupby(l)]
# [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]





share|improve this answer
































    6














    If I am not mistaken, you only need to lookup the last value.



    test = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a'),(3, 'a'),(4,"a"),(4,"a")]

    result = []

    for i in test:
    if result and i[0] == result[-1][0]: #edited since OP considers (1,"a") and (1,"b") as duplicate
    #if result and i == result[-1]:
    continue
    else:
    result.append(i)

    print (result)


    Output:



    [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (3, 'a'), (4, 'a')]





    share|improve this answer
































      1














      You could also use enumerate and a list comprehension:



      >>> data = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
      >>> [v for ix, v in enumerate(data) if not ix or v[0] != data[ix-1][0]]
      [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





      share|improve this answer























      • Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

        – Sparkofska
        Apr 18 at 5:59


















      0














      I'd change Henry Yik's proposal a little bit, making it a bit simpler. Not sure if I am missing something.



      inputList = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
      outputList = []
      lastItem = None

      for item in inputList:
      if not item == lastItem:
      outputList.append(item)
      lastItem = item
      print(outputList)





      share|improve this answer






























        0














        You can easily zip the list with itself. Every element, except the first one, is zipped with its predecessor:



        >>> L = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
        >>> list(zip(L[1:], L))
        [((2, 'b'), (1, 'a')), ((2, 'b'), (2, 'b')), ((2, 'c'), (2, 'b')), ((3, 'd'), (2, 'c')), ((2, 'e'), (3, 'd'))]


        The first element is always part of the result, and then you filter the pairs on the condition and return the first element:



        >>> [L[0]]+[e for e, f in zip(L[1:], L) if e[0]!=f[0]]
        [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





        share|improve this answer






























          0














          If you just want to stick to list comprehension, you can use something like this:



          >>> li = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
          >>> [li[i] for i in range(len(li)) if not i or li[i] != li[i-1]]
          [(1, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]


          Please not that not i is the pythonic way of writing i == 0.






          share|improve this answer























            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%2f55723664%2fhow-to-remove-list-items-depending-on-predecessor-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            13














            You can use itertools.groupby (demonstration with more data):



            from itertools import groupby
            from operator import itemgetter

            data = [(1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (3, 'a')]

            [next(group) for key, group in groupby(data, key=itemgetter(0))]


            Output:



            [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (2, 'a'), (3, 'a')]


            For completeness, an iterative approach based on other answers:



            result = []

            for first, second in zip(data, data[1:]):
            if first[0] != second[0]:
            result.append(first)

            result


            Output:



            [(1, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a')]


            Note that this keeps the last duplicate, instead of the first.






            share|improve this answer

























            • You don't need any key parameter, just take the key of each group

              – yatu
              Apr 17 at 9:05












            • @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

              – gmds
              Apr 17 at 9:06











            • I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

              – yatu
              Apr 17 at 9:09
















            13














            You can use itertools.groupby (demonstration with more data):



            from itertools import groupby
            from operator import itemgetter

            data = [(1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (3, 'a')]

            [next(group) for key, group in groupby(data, key=itemgetter(0))]


            Output:



            [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (2, 'a'), (3, 'a')]


            For completeness, an iterative approach based on other answers:



            result = []

            for first, second in zip(data, data[1:]):
            if first[0] != second[0]:
            result.append(first)

            result


            Output:



            [(1, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a')]


            Note that this keeps the last duplicate, instead of the first.






            share|improve this answer

























            • You don't need any key parameter, just take the key of each group

              – yatu
              Apr 17 at 9:05












            • @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

              – gmds
              Apr 17 at 9:06











            • I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

              – yatu
              Apr 17 at 9:09














            13












            13








            13







            You can use itertools.groupby (demonstration with more data):



            from itertools import groupby
            from operator import itemgetter

            data = [(1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (3, 'a')]

            [next(group) for key, group in groupby(data, key=itemgetter(0))]


            Output:



            [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (2, 'a'), (3, 'a')]


            For completeness, an iterative approach based on other answers:



            result = []

            for first, second in zip(data, data[1:]):
            if first[0] != second[0]:
            result.append(first)

            result


            Output:



            [(1, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a')]


            Note that this keeps the last duplicate, instead of the first.






            share|improve this answer















            You can use itertools.groupby (demonstration with more data):



            from itertools import groupby
            from operator import itemgetter

            data = [(1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (3, 'a')]

            [next(group) for key, group in groupby(data, key=itemgetter(0))]


            Output:



            [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (2, 'a'), (3, 'a')]


            For completeness, an iterative approach based on other answers:



            result = []

            for first, second in zip(data, data[1:]):
            if first[0] != second[0]:
            result.append(first)

            result


            Output:



            [(1, 'a'), (2, 'b'), (3, 'a'), (4, 'a'), (2, 'a')]


            Note that this keeps the last duplicate, instead of the first.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 17 at 9:35

























            answered Apr 17 at 9:04









            gmdsgmds

            7,121831




            7,121831












            • You don't need any key parameter, just take the key of each group

              – yatu
              Apr 17 at 9:05












            • @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

              – gmds
              Apr 17 at 9:06











            • I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

              – yatu
              Apr 17 at 9:09


















            • You don't need any key parameter, just take the key of each group

              – yatu
              Apr 17 at 9:05












            • @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

              – gmds
              Apr 17 at 9:06











            • I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

              – yatu
              Apr 17 at 9:09

















            You don't need any key parameter, just take the key of each group

            – yatu
            Apr 17 at 9:05






            You don't need any key parameter, just take the key of each group

            – yatu
            Apr 17 at 9:05














            @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

            – gmds
            Apr 17 at 9:06





            @yatu The question says "the duplicate value is an attribute of the list", which means that that wouldn't work if (2, 'a') and (2, 'b') are considered equal.

            – gmds
            Apr 17 at 9:06













            I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

            – yatu
            Apr 17 at 9:09






            I see yes in that case indeed it makes sense @gmds. Hard to tell however with this example. IMO if tht was what OP meant a more general example would make more sense

            – yatu
            Apr 17 at 9:09














            9














            In order to remove consecutive duplicates, you could use itertools.groupby:



            l = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]
            from itertools import groupby
            [tuple(k) for k, _ in groupby(l)]
            # [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]





            share|improve this answer





























              9














              In order to remove consecutive duplicates, you could use itertools.groupby:



              l = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]
              from itertools import groupby
              [tuple(k) for k, _ in groupby(l)]
              # [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]





              share|improve this answer



























                9












                9








                9







                In order to remove consecutive duplicates, you could use itertools.groupby:



                l = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]
                from itertools import groupby
                [tuple(k) for k, _ in groupby(l)]
                # [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]





                share|improve this answer















                In order to remove consecutive duplicates, you could use itertools.groupby:



                l = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]
                from itertools import groupby
                [tuple(k) for k, _ in groupby(l)]
                # [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')]






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 17 at 9:08

























                answered Apr 17 at 8:59









                yatuyatu

                16.7k41742




                16.7k41742





















                    6














                    If I am not mistaken, you only need to lookup the last value.



                    test = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a'),(3, 'a'),(4,"a"),(4,"a")]

                    result = []

                    for i in test:
                    if result and i[0] == result[-1][0]: #edited since OP considers (1,"a") and (1,"b") as duplicate
                    #if result and i == result[-1]:
                    continue
                    else:
                    result.append(i)

                    print (result)


                    Output:



                    [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (3, 'a'), (4, 'a')]





                    share|improve this answer





























                      6














                      If I am not mistaken, you only need to lookup the last value.



                      test = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a'),(3, 'a'),(4,"a"),(4,"a")]

                      result = []

                      for i in test:
                      if result and i[0] == result[-1][0]: #edited since OP considers (1,"a") and (1,"b") as duplicate
                      #if result and i == result[-1]:
                      continue
                      else:
                      result.append(i)

                      print (result)


                      Output:



                      [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (3, 'a'), (4, 'a')]





                      share|improve this answer



























                        6












                        6








                        6







                        If I am not mistaken, you only need to lookup the last value.



                        test = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a'),(3, 'a'),(4,"a"),(4,"a")]

                        result = []

                        for i in test:
                        if result and i[0] == result[-1][0]: #edited since OP considers (1,"a") and (1,"b") as duplicate
                        #if result and i == result[-1]:
                        continue
                        else:
                        result.append(i)

                        print (result)


                        Output:



                        [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (3, 'a'), (4, 'a')]





                        share|improve this answer















                        If I am not mistaken, you only need to lookup the last value.



                        test = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (4, 'a'),(3, 'a'),(4,"a"),(4,"a")]

                        result = []

                        for i in test:
                        if result and i[0] == result[-1][0]: #edited since OP considers (1,"a") and (1,"b") as duplicate
                        #if result and i == result[-1]:
                        continue
                        else:
                        result.append(i)

                        print (result)


                        Output:



                        [(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (3, 'a'), (4, 'a')]






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 17 at 9:21

























                        answered Apr 17 at 9:08









                        Henry YikHenry Yik

                        1,6322414




                        1,6322414





















                            1














                            You could also use enumerate and a list comprehension:



                            >>> data = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                            >>> [v for ix, v in enumerate(data) if not ix or v[0] != data[ix-1][0]]
                            [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                            share|improve this answer























                            • Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                              – Sparkofska
                              Apr 18 at 5:59















                            1














                            You could also use enumerate and a list comprehension:



                            >>> data = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                            >>> [v for ix, v in enumerate(data) if not ix or v[0] != data[ix-1][0]]
                            [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                            share|improve this answer























                            • Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                              – Sparkofska
                              Apr 18 at 5:59













                            1












                            1








                            1







                            You could also use enumerate and a list comprehension:



                            >>> data = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                            >>> [v for ix, v in enumerate(data) if not ix or v[0] != data[ix-1][0]]
                            [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                            share|improve this answer













                            You could also use enumerate and a list comprehension:



                            >>> data = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                            >>> [v for ix, v in enumerate(data) if not ix or v[0] != data[ix-1][0]]
                            [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 18 at 5:45









                            CloudomationCloudomation

                            777111




                            777111












                            • Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                              – Sparkofska
                              Apr 18 at 5:59

















                            • Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                              – Sparkofska
                              Apr 18 at 5:59
















                            Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                            – Sparkofska
                            Apr 18 at 5:59





                            Nice one, because no need for any imports. Also v[0] can be replaced by any v.get_attribute(), which makes it quite universal.

                            – Sparkofska
                            Apr 18 at 5:59











                            0














                            I'd change Henry Yik's proposal a little bit, making it a bit simpler. Not sure if I am missing something.



                            inputList = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                            outputList = []
                            lastItem = None

                            for item in inputList:
                            if not item == lastItem:
                            outputList.append(item)
                            lastItem = item
                            print(outputList)





                            share|improve this answer



























                              0














                              I'd change Henry Yik's proposal a little bit, making it a bit simpler. Not sure if I am missing something.



                              inputList = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                              outputList = []
                              lastItem = None

                              for item in inputList:
                              if not item == lastItem:
                              outputList.append(item)
                              lastItem = item
                              print(outputList)





                              share|improve this answer

























                                0












                                0








                                0







                                I'd change Henry Yik's proposal a little bit, making it a bit simpler. Not sure if I am missing something.



                                inputList = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                outputList = []
                                lastItem = None

                                for item in inputList:
                                if not item == lastItem:
                                outputList.append(item)
                                lastItem = item
                                print(outputList)





                                share|improve this answer













                                I'd change Henry Yik's proposal a little bit, making it a bit simpler. Not sure if I am missing something.



                                inputList = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                outputList = []
                                lastItem = None

                                for item in inputList:
                                if not item == lastItem:
                                outputList.append(item)
                                lastItem = item
                                print(outputList)






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Apr 17 at 9:16









                                carnicercarnicer

                                1396




                                1396





















                                    0














                                    You can easily zip the list with itself. Every element, except the first one, is zipped with its predecessor:



                                    >>> L = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                                    >>> list(zip(L[1:], L))
                                    [((2, 'b'), (1, 'a')), ((2, 'b'), (2, 'b')), ((2, 'c'), (2, 'b')), ((3, 'd'), (2, 'c')), ((2, 'e'), (3, 'd'))]


                                    The first element is always part of the result, and then you filter the pairs on the condition and return the first element:



                                    >>> [L[0]]+[e for e, f in zip(L[1:], L) if e[0]!=f[0]]
                                    [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                                    share|improve this answer



























                                      0














                                      You can easily zip the list with itself. Every element, except the first one, is zipped with its predecessor:



                                      >>> L = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                                      >>> list(zip(L[1:], L))
                                      [((2, 'b'), (1, 'a')), ((2, 'b'), (2, 'b')), ((2, 'c'), (2, 'b')), ((3, 'd'), (2, 'c')), ((2, 'e'), (3, 'd'))]


                                      The first element is always part of the result, and then you filter the pairs on the condition and return the first element:



                                      >>> [L[0]]+[e for e, f in zip(L[1:], L) if e[0]!=f[0]]
                                      [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                                      share|improve this answer

























                                        0












                                        0








                                        0







                                        You can easily zip the list with itself. Every element, except the first one, is zipped with its predecessor:



                                        >>> L = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                                        >>> list(zip(L[1:], L))
                                        [((2, 'b'), (1, 'a')), ((2, 'b'), (2, 'b')), ((2, 'c'), (2, 'b')), ((3, 'd'), (2, 'c')), ((2, 'e'), (3, 'd'))]


                                        The first element is always part of the result, and then you filter the pairs on the condition and return the first element:



                                        >>> [L[0]]+[e for e, f in zip(L[1:], L) if e[0]!=f[0]]
                                        [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]





                                        share|improve this answer













                                        You can easily zip the list with itself. Every element, except the first one, is zipped with its predecessor:



                                        >>> L = [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
                                        >>> list(zip(L[1:], L))
                                        [((2, 'b'), (1, 'a')), ((2, 'b'), (2, 'b')), ((2, 'c'), (2, 'b')), ((3, 'd'), (2, 'c')), ((2, 'e'), (3, 'd'))]


                                        The first element is always part of the result, and then you filter the pairs on the condition and return the first element:



                                        >>> [L[0]]+[e for e, f in zip(L[1:], L) if e[0]!=f[0]]
                                        [(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Apr 17 at 15:23









                                        jferardjferard

                                        2,2411315




                                        2,2411315





















                                            0














                                            If you just want to stick to list comprehension, you can use something like this:



                                            >>> li = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                            >>> [li[i] for i in range(len(li)) if not i or li[i] != li[i-1]]
                                            [(1, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]


                                            Please not that not i is the pythonic way of writing i == 0.






                                            share|improve this answer



























                                              0














                                              If you just want to stick to list comprehension, you can use something like this:



                                              >>> li = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                              >>> [li[i] for i in range(len(li)) if not i or li[i] != li[i-1]]
                                              [(1, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]


                                              Please not that not i is the pythonic way of writing i == 0.






                                              share|improve this answer

























                                                0












                                                0








                                                0







                                                If you just want to stick to list comprehension, you can use something like this:



                                                >>> li = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                                >>> [li[i] for i in range(len(li)) if not i or li[i] != li[i-1]]
                                                [(1, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]


                                                Please not that not i is the pythonic way of writing i == 0.






                                                share|improve this answer













                                                If you just want to stick to list comprehension, you can use something like this:



                                                >>> li = [(1, 'a'), (2, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]
                                                >>> [li[i] for i in range(len(li)) if not i or li[i] != li[i-1]]
                                                [(1, 'a'), (2, 'a'), (3, 'a'), (2, 'a')]


                                                Please not that not i is the pythonic way of writing i == 0.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Apr 17 at 18:35









                                                kaHaleMaKaikaHaleMaKai

                                                12




                                                12



























                                                    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%2f55723664%2fhow-to-remove-list-items-depending-on-predecessor-in-python%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







                                                    Popular posts from this blog

                                                    Sum ergo cogito? 1 nng

                                                    三茅街道4182Guuntc Dn precexpngmageondP