How to group identical values from a list into their own lists?











up vote
4
down vote

favorite












Say I have a list [2, 3, 7, 2, 3, 8, 7, 3]



I would like to produce lists that contain identical values from the list above.



Expected Output something like:



[2, 2]
[3, 3, 3]
[7, 7]
[8]


The order that these lists are produced doesn't matter.










share|improve this question






















  • Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
    – Adriano
    Nov 22 at 5:17












  • Numbers (Integers to be precise)
    – Oamar Kanji
    Nov 22 at 5:19















up vote
4
down vote

favorite












Say I have a list [2, 3, 7, 2, 3, 8, 7, 3]



I would like to produce lists that contain identical values from the list above.



Expected Output something like:



[2, 2]
[3, 3, 3]
[7, 7]
[8]


The order that these lists are produced doesn't matter.










share|improve this question






















  • Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
    – Adriano
    Nov 22 at 5:17












  • Numbers (Integers to be precise)
    – Oamar Kanji
    Nov 22 at 5:19













up vote
4
down vote

favorite









up vote
4
down vote

favorite











Say I have a list [2, 3, 7, 2, 3, 8, 7, 3]



I would like to produce lists that contain identical values from the list above.



Expected Output something like:



[2, 2]
[3, 3, 3]
[7, 7]
[8]


The order that these lists are produced doesn't matter.










share|improve this question













Say I have a list [2, 3, 7, 2, 3, 8, 7, 3]



I would like to produce lists that contain identical values from the list above.



Expected Output something like:



[2, 2]
[3, 3, 3]
[7, 7]
[8]


The order that these lists are produced doesn't matter.







python list-comprehension






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 5:15









Oamar Kanji

183210




183210












  • Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
    – Adriano
    Nov 22 at 5:17












  • Numbers (Integers to be precise)
    – Oamar Kanji
    Nov 22 at 5:19


















  • Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
    – Adriano
    Nov 22 at 5:17












  • Numbers (Integers to be precise)
    – Oamar Kanji
    Nov 22 at 5:19
















Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
– Adriano
Nov 22 at 5:17






Are you working with numbers, or strings? Also, what do you need this for... can you give us more details?
– Adriano
Nov 22 at 5:17














Numbers (Integers to be precise)
– Oamar Kanji
Nov 22 at 5:19




Numbers (Integers to be precise)
– Oamar Kanji
Nov 22 at 5:19












7 Answers
7






active

oldest

votes

















up vote
5
down vote



accepted










Try this



l = [2, 3, 7, 2, 3, 8, 7, 3]
for i in set(l):
print([i]*l.count(i))


Output:



[8]
[2, 2]
[3, 3, 3]
[7, 7]





share|improve this answer



















  • 1




    [[i]*l.count(if) for i in set(l)]
    – Netwave
    Nov 22 at 5:29






  • 3




    There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
    – Netwave
    Nov 22 at 5:50


















up vote
4
down vote













You can use itertools.groupby with sorted list:



>>> for _, l in itertools.groupby(sorted(l)):
... print(list(l))
...
[2, 2]
[3, 3, 3]
[7, 7]
[8]


Or an O(n) solution with collections.defaultdict:



>>> l = [2, 3, 7, 2, 3, 8, 7, 3]
>>> d = defaultdict(list)
>>> for e in l:
... d[e].append(e)
...
>>> d
defaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})
>>> d.values()
dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])


Or a list comprehension with collections.Counter:



>>> from collections import Counter
>>> [[i]*n for i,n in Counter(l).items()]
[[2, 2], [3, 3, 3], [7, 7], [8]]


As I post, the defaultdict solution is O(n) and faster than the other aproaches. Here are the tests:



from timeit import timeit


setup = (
"from collections import Counter, defaultdict;"
"from itertools import groupby;"
"l = [2, 3, 7, 2, 3, 8, 7, 3];"
)

defaultdict_call = (
"d = defaultdict(list); "
"nfor e in l: d[e].append(e);"
)
groupby_call = "[list(g) for _,g in groupby(sorted(l))]"
counter_call = "[[i]*n for i,n in Counter(l).items()]"


for call in (defaultdict_call, groupby_call, counter_call):
print(call)
print(timeit(call, setup))


Results:



d = defaultdict(list); 
for e in l: d[e].append(e);
7.02662614302244
[list(g) for _,g in groupby(sorted(l))]
10.126392606005538
[[i]*n for i,n in Counter(l).items()]
19.55539561196929


Here is the live test






share|improve this answer






























    up vote
    3
    down vote













    One way to do this is to use a simple dictionary:



    l = [2, 3, 7, 2, 3, 8, 7, 3]

    groups = {}
    for n in l:
    groups.setdefault(n, ).append(n)

    print(list(groups.values()))
    # [[2, 2], [3, 3, 3], [7, 7], [8]]





    share|improve this answer




























      up vote
      3
      down vote













      Here's a short way of doing it by using Counter



      from collections import Counter
      my_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}

      new_list = [[k] * v for k,v in my_dict.items()]


      Outputs:



      [[2, 2], [3, 3, 3], [7, 7], [8]]





      share|improve this answer






























        up vote
        3
        down vote













        This answer is with list-comprehension:



        l = [2, 3, 7, 2, 3, 8, 7, 3]

        print(*[[i]*l.count(i) for i in set(l)], sep='n')


        OUTPUT :



        C:UsersDesktop>py x.py
        [8]
        [2, 2]
        [3, 3, 3]
        [7, 7]


        Moreover, the output can be made exactly as yours with sorted() method



        l = [2, 3, 7, 2, 3, 8, 7, 3]

        print(*sorted([[i]*l.count(i) for i in set(l)]), sep='n')


        OUTPUT:



        C:UsersDesktop>py x.py
        [2, 2]
        [3, 3, 3]
        [7, 7]
        [8]


        EDIT : As the answer gets upvoted I want to explain the code in detail to be helpful as much as I can.



        The code is this:



         print(*[[i]*l.count(i) for i in set(l)], sep='n')


        Using set(l) eliminates duplicated values and remains only [2, 3, 7, 8] in the list. Later, in [i] we put each element of set(l) in a new list. We count how many time i element(i is a element in set(l)) occurs in native list l (l = [2, 3, 7, 2, 3, 8, 7, 3]). And in [i]*l.count(i) i become l.count(i) times in the new list. List-comprehension method gets the all values after iterations are done and pack it in a list and returns list. * sign at the beginning is for unpacking the values in the returned list. And finally *print()* keyword sep='n' put a 'n' after each elements in the unpacked list. Without it this could have been done like:



        for j in [[i]*l.count(i) for i in set(l)]:
        print(j)





        share|improve this answer






























          up vote
          2
          down vote













          Doing this operation in Numpy array would be efficient



          a= np.array([2, 3, 7, 2, 3, 8, 7, 3])
          [a[a==i] for i in np.unique(a)]


          Output:



          [array([2, 2]), array([3, 3, 3]), array([7, 7]), array([8])]





          share|improve this answer




























            up vote
            2
            down vote













            I think you may try collections.Counter, and get different keys and its count in this list.



            from collections import Counter
            l = [2, 3, 7, 2, 3, 8, 7, 3]
            c =Counter(l)
            print(c) ## result: {3: 3, 2: 2, 7: 2, 8: 1}





            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',
              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%2f53424276%2fhow-to-group-identical-values-from-a-list-into-their-own-lists%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








              up vote
              5
              down vote



              accepted










              Try this



              l = [2, 3, 7, 2, 3, 8, 7, 3]
              for i in set(l):
              print([i]*l.count(i))


              Output:



              [8]
              [2, 2]
              [3, 3, 3]
              [7, 7]





              share|improve this answer



















              • 1




                [[i]*l.count(if) for i in set(l)]
                – Netwave
                Nov 22 at 5:29






              • 3




                There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
                – Netwave
                Nov 22 at 5:50















              up vote
              5
              down vote



              accepted










              Try this



              l = [2, 3, 7, 2, 3, 8, 7, 3]
              for i in set(l):
              print([i]*l.count(i))


              Output:



              [8]
              [2, 2]
              [3, 3, 3]
              [7, 7]





              share|improve this answer



















              • 1




                [[i]*l.count(if) for i in set(l)]
                – Netwave
                Nov 22 at 5:29






              • 3




                There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
                – Netwave
                Nov 22 at 5:50













              up vote
              5
              down vote



              accepted







              up vote
              5
              down vote



              accepted






              Try this



              l = [2, 3, 7, 2, 3, 8, 7, 3]
              for i in set(l):
              print([i]*l.count(i))


              Output:



              [8]
              [2, 2]
              [3, 3, 3]
              [7, 7]





              share|improve this answer














              Try this



              l = [2, 3, 7, 2, 3, 8, 7, 3]
              for i in set(l):
              print([i]*l.count(i))


              Output:



              [8]
              [2, 2]
              [3, 3, 3]
              [7, 7]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 22 at 5:52

























              answered Nov 22 at 5:19









              Anjaneyulu Batta

              3,11011333




              3,11011333








              • 1




                [[i]*l.count(if) for i in set(l)]
                – Netwave
                Nov 22 at 5:29






              • 3




                There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
                – Netwave
                Nov 22 at 5:50














              • 1




                [[i]*l.count(if) for i in set(l)]
                – Netwave
                Nov 22 at 5:29






              • 3




                There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
                – Netwave
                Nov 22 at 5:50








              1




              1




              [[i]*l.count(if) for i in set(l)]
              – Netwave
              Nov 22 at 5:29




              [[i]*l.count(if) for i in set(l)]
              – Netwave
              Nov 22 at 5:29




              3




              3




              There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
              – Netwave
              Nov 22 at 5:50




              There is a "problem" with this solution. It will iterate on l several times. It is not a problem for small lists. But will get slower for big ones. The O(n) solution with defaultdict will perform much faster.
              – Netwave
              Nov 22 at 5:50












              up vote
              4
              down vote













              You can use itertools.groupby with sorted list:



              >>> for _, l in itertools.groupby(sorted(l)):
              ... print(list(l))
              ...
              [2, 2]
              [3, 3, 3]
              [7, 7]
              [8]


              Or an O(n) solution with collections.defaultdict:



              >>> l = [2, 3, 7, 2, 3, 8, 7, 3]
              >>> d = defaultdict(list)
              >>> for e in l:
              ... d[e].append(e)
              ...
              >>> d
              defaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})
              >>> d.values()
              dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])


              Or a list comprehension with collections.Counter:



              >>> from collections import Counter
              >>> [[i]*n for i,n in Counter(l).items()]
              [[2, 2], [3, 3, 3], [7, 7], [8]]


              As I post, the defaultdict solution is O(n) and faster than the other aproaches. Here are the tests:



              from timeit import timeit


              setup = (
              "from collections import Counter, defaultdict;"
              "from itertools import groupby;"
              "l = [2, 3, 7, 2, 3, 8, 7, 3];"
              )

              defaultdict_call = (
              "d = defaultdict(list); "
              "nfor e in l: d[e].append(e);"
              )
              groupby_call = "[list(g) for _,g in groupby(sorted(l))]"
              counter_call = "[[i]*n for i,n in Counter(l).items()]"


              for call in (defaultdict_call, groupby_call, counter_call):
              print(call)
              print(timeit(call, setup))


              Results:



              d = defaultdict(list); 
              for e in l: d[e].append(e);
              7.02662614302244
              [list(g) for _,g in groupby(sorted(l))]
              10.126392606005538
              [[i]*n for i,n in Counter(l).items()]
              19.55539561196929


              Here is the live test






              share|improve this answer



























                up vote
                4
                down vote













                You can use itertools.groupby with sorted list:



                >>> for _, l in itertools.groupby(sorted(l)):
                ... print(list(l))
                ...
                [2, 2]
                [3, 3, 3]
                [7, 7]
                [8]


                Or an O(n) solution with collections.defaultdict:



                >>> l = [2, 3, 7, 2, 3, 8, 7, 3]
                >>> d = defaultdict(list)
                >>> for e in l:
                ... d[e].append(e)
                ...
                >>> d
                defaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})
                >>> d.values()
                dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])


                Or a list comprehension with collections.Counter:



                >>> from collections import Counter
                >>> [[i]*n for i,n in Counter(l).items()]
                [[2, 2], [3, 3, 3], [7, 7], [8]]


                As I post, the defaultdict solution is O(n) and faster than the other aproaches. Here are the tests:



                from timeit import timeit


                setup = (
                "from collections import Counter, defaultdict;"
                "from itertools import groupby;"
                "l = [2, 3, 7, 2, 3, 8, 7, 3];"
                )

                defaultdict_call = (
                "d = defaultdict(list); "
                "nfor e in l: d[e].append(e);"
                )
                groupby_call = "[list(g) for _,g in groupby(sorted(l))]"
                counter_call = "[[i]*n for i,n in Counter(l).items()]"


                for call in (defaultdict_call, groupby_call, counter_call):
                print(call)
                print(timeit(call, setup))


                Results:



                d = defaultdict(list); 
                for e in l: d[e].append(e);
                7.02662614302244
                [list(g) for _,g in groupby(sorted(l))]
                10.126392606005538
                [[i]*n for i,n in Counter(l).items()]
                19.55539561196929


                Here is the live test






                share|improve this answer

























                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  You can use itertools.groupby with sorted list:



                  >>> for _, l in itertools.groupby(sorted(l)):
                  ... print(list(l))
                  ...
                  [2, 2]
                  [3, 3, 3]
                  [7, 7]
                  [8]


                  Or an O(n) solution with collections.defaultdict:



                  >>> l = [2, 3, 7, 2, 3, 8, 7, 3]
                  >>> d = defaultdict(list)
                  >>> for e in l:
                  ... d[e].append(e)
                  ...
                  >>> d
                  defaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})
                  >>> d.values()
                  dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])


                  Or a list comprehension with collections.Counter:



                  >>> from collections import Counter
                  >>> [[i]*n for i,n in Counter(l).items()]
                  [[2, 2], [3, 3, 3], [7, 7], [8]]


                  As I post, the defaultdict solution is O(n) and faster than the other aproaches. Here are the tests:



                  from timeit import timeit


                  setup = (
                  "from collections import Counter, defaultdict;"
                  "from itertools import groupby;"
                  "l = [2, 3, 7, 2, 3, 8, 7, 3];"
                  )

                  defaultdict_call = (
                  "d = defaultdict(list); "
                  "nfor e in l: d[e].append(e);"
                  )
                  groupby_call = "[list(g) for _,g in groupby(sorted(l))]"
                  counter_call = "[[i]*n for i,n in Counter(l).items()]"


                  for call in (defaultdict_call, groupby_call, counter_call):
                  print(call)
                  print(timeit(call, setup))


                  Results:



                  d = defaultdict(list); 
                  for e in l: d[e].append(e);
                  7.02662614302244
                  [list(g) for _,g in groupby(sorted(l))]
                  10.126392606005538
                  [[i]*n for i,n in Counter(l).items()]
                  19.55539561196929


                  Here is the live test






                  share|improve this answer














                  You can use itertools.groupby with sorted list:



                  >>> for _, l in itertools.groupby(sorted(l)):
                  ... print(list(l))
                  ...
                  [2, 2]
                  [3, 3, 3]
                  [7, 7]
                  [8]


                  Or an O(n) solution with collections.defaultdict:



                  >>> l = [2, 3, 7, 2, 3, 8, 7, 3]
                  >>> d = defaultdict(list)
                  >>> for e in l:
                  ... d[e].append(e)
                  ...
                  >>> d
                  defaultdict(<class 'list'>, {2: [2, 2], 3: [3, 3, 3], 7: [7, 7], 8: [8]})
                  >>> d.values()
                  dict_values([[2, 2], [3, 3, 3], [7, 7], [8]])


                  Or a list comprehension with collections.Counter:



                  >>> from collections import Counter
                  >>> [[i]*n for i,n in Counter(l).items()]
                  [[2, 2], [3, 3, 3], [7, 7], [8]]


                  As I post, the defaultdict solution is O(n) and faster than the other aproaches. Here are the tests:



                  from timeit import timeit


                  setup = (
                  "from collections import Counter, defaultdict;"
                  "from itertools import groupby;"
                  "l = [2, 3, 7, 2, 3, 8, 7, 3];"
                  )

                  defaultdict_call = (
                  "d = defaultdict(list); "
                  "nfor e in l: d[e].append(e);"
                  )
                  groupby_call = "[list(g) for _,g in groupby(sorted(l))]"
                  counter_call = "[[i]*n for i,n in Counter(l).items()]"


                  for call in (defaultdict_call, groupby_call, counter_call):
                  print(call)
                  print(timeit(call, setup))


                  Results:



                  d = defaultdict(list); 
                  for e in l: d[e].append(e);
                  7.02662614302244
                  [list(g) for _,g in groupby(sorted(l))]
                  10.126392606005538
                  [[i]*n for i,n in Counter(l).items()]
                  19.55539561196929


                  Here is the live test







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 22 at 6:01

























                  answered Nov 22 at 5:21









                  Netwave

                  12k22043




                  12k22043






















                      up vote
                      3
                      down vote













                      One way to do this is to use a simple dictionary:



                      l = [2, 3, 7, 2, 3, 8, 7, 3]

                      groups = {}
                      for n in l:
                      groups.setdefault(n, ).append(n)

                      print(list(groups.values()))
                      # [[2, 2], [3, 3, 3], [7, 7], [8]]





                      share|improve this answer

























                        up vote
                        3
                        down vote













                        One way to do this is to use a simple dictionary:



                        l = [2, 3, 7, 2, 3, 8, 7, 3]

                        groups = {}
                        for n in l:
                        groups.setdefault(n, ).append(n)

                        print(list(groups.values()))
                        # [[2, 2], [3, 3, 3], [7, 7], [8]]





                        share|improve this answer























                          up vote
                          3
                          down vote










                          up vote
                          3
                          down vote









                          One way to do this is to use a simple dictionary:



                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                          groups = {}
                          for n in l:
                          groups.setdefault(n, ).append(n)

                          print(list(groups.values()))
                          # [[2, 2], [3, 3, 3], [7, 7], [8]]





                          share|improve this answer












                          One way to do this is to use a simple dictionary:



                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                          groups = {}
                          for n in l:
                          groups.setdefault(n, ).append(n)

                          print(list(groups.values()))
                          # [[2, 2], [3, 3, 3], [7, 7], [8]]






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 22 at 5:35









                          slider

                          7,3851129




                          7,3851129






















                              up vote
                              3
                              down vote













                              Here's a short way of doing it by using Counter



                              from collections import Counter
                              my_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}

                              new_list = [[k] * v for k,v in my_dict.items()]


                              Outputs:



                              [[2, 2], [3, 3, 3], [7, 7], [8]]





                              share|improve this answer



























                                up vote
                                3
                                down vote













                                Here's a short way of doing it by using Counter



                                from collections import Counter
                                my_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}

                                new_list = [[k] * v for k,v in my_dict.items()]


                                Outputs:



                                [[2, 2], [3, 3, 3], [7, 7], [8]]





                                share|improve this answer

























                                  up vote
                                  3
                                  down vote










                                  up vote
                                  3
                                  down vote









                                  Here's a short way of doing it by using Counter



                                  from collections import Counter
                                  my_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}

                                  new_list = [[k] * v for k,v in my_dict.items()]


                                  Outputs:



                                  [[2, 2], [3, 3, 3], [7, 7], [8]]





                                  share|improve this answer














                                  Here's a short way of doing it by using Counter



                                  from collections import Counter
                                  my_dict = Counter([2, 3, 7, 2, 3, 8, 7, 3]) # returns {3: 3, 2: 2, 7: 2, 8: 1}

                                  new_list = [[k] * v for k,v in my_dict.items()]


                                  Outputs:



                                  [[2, 2], [3, 3, 3], [7, 7], [8]]






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 22 at 5:41

























                                  answered Nov 22 at 5:21









                                  Vineeth Sai

                                  2,24931023




                                  2,24931023






















                                      up vote
                                      3
                                      down vote













                                      This answer is with list-comprehension:



                                      l = [2, 3, 7, 2, 3, 8, 7, 3]

                                      print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                      OUTPUT :



                                      C:UsersDesktop>py x.py
                                      [8]
                                      [2, 2]
                                      [3, 3, 3]
                                      [7, 7]


                                      Moreover, the output can be made exactly as yours with sorted() method



                                      l = [2, 3, 7, 2, 3, 8, 7, 3]

                                      print(*sorted([[i]*l.count(i) for i in set(l)]), sep='n')


                                      OUTPUT:



                                      C:UsersDesktop>py x.py
                                      [2, 2]
                                      [3, 3, 3]
                                      [7, 7]
                                      [8]


                                      EDIT : As the answer gets upvoted I want to explain the code in detail to be helpful as much as I can.



                                      The code is this:



                                       print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                      Using set(l) eliminates duplicated values and remains only [2, 3, 7, 8] in the list. Later, in [i] we put each element of set(l) in a new list. We count how many time i element(i is a element in set(l)) occurs in native list l (l = [2, 3, 7, 2, 3, 8, 7, 3]). And in [i]*l.count(i) i become l.count(i) times in the new list. List-comprehension method gets the all values after iterations are done and pack it in a list and returns list. * sign at the beginning is for unpacking the values in the returned list. And finally *print()* keyword sep='n' put a 'n' after each elements in the unpacked list. Without it this could have been done like:



                                      for j in [[i]*l.count(i) for i in set(l)]:
                                      print(j)





                                      share|improve this answer



























                                        up vote
                                        3
                                        down vote













                                        This answer is with list-comprehension:



                                        l = [2, 3, 7, 2, 3, 8, 7, 3]

                                        print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                        OUTPUT :



                                        C:UsersDesktop>py x.py
                                        [8]
                                        [2, 2]
                                        [3, 3, 3]
                                        [7, 7]


                                        Moreover, the output can be made exactly as yours with sorted() method



                                        l = [2, 3, 7, 2, 3, 8, 7, 3]

                                        print(*sorted([[i]*l.count(i) for i in set(l)]), sep='n')


                                        OUTPUT:



                                        C:UsersDesktop>py x.py
                                        [2, 2]
                                        [3, 3, 3]
                                        [7, 7]
                                        [8]


                                        EDIT : As the answer gets upvoted I want to explain the code in detail to be helpful as much as I can.



                                        The code is this:



                                         print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                        Using set(l) eliminates duplicated values and remains only [2, 3, 7, 8] in the list. Later, in [i] we put each element of set(l) in a new list. We count how many time i element(i is a element in set(l)) occurs in native list l (l = [2, 3, 7, 2, 3, 8, 7, 3]). And in [i]*l.count(i) i become l.count(i) times in the new list. List-comprehension method gets the all values after iterations are done and pack it in a list and returns list. * sign at the beginning is for unpacking the values in the returned list. And finally *print()* keyword sep='n' put a 'n' after each elements in the unpacked list. Without it this could have been done like:



                                        for j in [[i]*l.count(i) for i in set(l)]:
                                        print(j)





                                        share|improve this answer

























                                          up vote
                                          3
                                          down vote










                                          up vote
                                          3
                                          down vote









                                          This answer is with list-comprehension:



                                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                                          print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                          OUTPUT :



                                          C:UsersDesktop>py x.py
                                          [8]
                                          [2, 2]
                                          [3, 3, 3]
                                          [7, 7]


                                          Moreover, the output can be made exactly as yours with sorted() method



                                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                                          print(*sorted([[i]*l.count(i) for i in set(l)]), sep='n')


                                          OUTPUT:



                                          C:UsersDesktop>py x.py
                                          [2, 2]
                                          [3, 3, 3]
                                          [7, 7]
                                          [8]


                                          EDIT : As the answer gets upvoted I want to explain the code in detail to be helpful as much as I can.



                                          The code is this:



                                           print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                          Using set(l) eliminates duplicated values and remains only [2, 3, 7, 8] in the list. Later, in [i] we put each element of set(l) in a new list. We count how many time i element(i is a element in set(l)) occurs in native list l (l = [2, 3, 7, 2, 3, 8, 7, 3]). And in [i]*l.count(i) i become l.count(i) times in the new list. List-comprehension method gets the all values after iterations are done and pack it in a list and returns list. * sign at the beginning is for unpacking the values in the returned list. And finally *print()* keyword sep='n' put a 'n' after each elements in the unpacked list. Without it this could have been done like:



                                          for j in [[i]*l.count(i) for i in set(l)]:
                                          print(j)





                                          share|improve this answer














                                          This answer is with list-comprehension:



                                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                                          print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                          OUTPUT :



                                          C:UsersDesktop>py x.py
                                          [8]
                                          [2, 2]
                                          [3, 3, 3]
                                          [7, 7]


                                          Moreover, the output can be made exactly as yours with sorted() method



                                          l = [2, 3, 7, 2, 3, 8, 7, 3]

                                          print(*sorted([[i]*l.count(i) for i in set(l)]), sep='n')


                                          OUTPUT:



                                          C:UsersDesktop>py x.py
                                          [2, 2]
                                          [3, 3, 3]
                                          [7, 7]
                                          [8]


                                          EDIT : As the answer gets upvoted I want to explain the code in detail to be helpful as much as I can.



                                          The code is this:



                                           print(*[[i]*l.count(i) for i in set(l)], sep='n')


                                          Using set(l) eliminates duplicated values and remains only [2, 3, 7, 8] in the list. Later, in [i] we put each element of set(l) in a new list. We count how many time i element(i is a element in set(l)) occurs in native list l (l = [2, 3, 7, 2, 3, 8, 7, 3]). And in [i]*l.count(i) i become l.count(i) times in the new list. List-comprehension method gets the all values after iterations are done and pack it in a list and returns list. * sign at the beginning is for unpacking the values in the returned list. And finally *print()* keyword sep='n' put a 'n' after each elements in the unpacked list. Without it this could have been done like:



                                          for j in [[i]*l.count(i) for i in set(l)]:
                                          print(j)






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 22 at 6:29

























                                          answered Nov 22 at 5:35









                                          Rarblack

                                          2,1283823




                                          2,1283823






















                                              up vote
                                              2
                                              down vote













                                              Doing this operation in Numpy array would be efficient



                                              a= np.array([2, 3, 7, 2, 3, 8, 7, 3])
                                              [a[a==i] for i in np.unique(a)]


                                              Output:



                                              [array([2, 2]), array([3, 3, 3]), array([7, 7]), array([8])]





                                              share|improve this answer

























                                                up vote
                                                2
                                                down vote













                                                Doing this operation in Numpy array would be efficient



                                                a= np.array([2, 3, 7, 2, 3, 8, 7, 3])
                                                [a[a==i] for i in np.unique(a)]


                                                Output:



                                                [array([2, 2]), array([3, 3, 3]), array([7, 7]), array([8])]





                                                share|improve this answer























                                                  up vote
                                                  2
                                                  down vote










                                                  up vote
                                                  2
                                                  down vote









                                                  Doing this operation in Numpy array would be efficient



                                                  a= np.array([2, 3, 7, 2, 3, 8, 7, 3])
                                                  [a[a==i] for i in np.unique(a)]


                                                  Output:



                                                  [array([2, 2]), array([3, 3, 3]), array([7, 7]), array([8])]





                                                  share|improve this answer












                                                  Doing this operation in Numpy array would be efficient



                                                  a= np.array([2, 3, 7, 2, 3, 8, 7, 3])
                                                  [a[a==i] for i in np.unique(a)]


                                                  Output:



                                                  [array([2, 2]), array([3, 3, 3]), array([7, 7]), array([8])]






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 22 at 5:20









                                                  AILearning

                                                  525420




                                                  525420






















                                                      up vote
                                                      2
                                                      down vote













                                                      I think you may try collections.Counter, and get different keys and its count in this list.



                                                      from collections import Counter
                                                      l = [2, 3, 7, 2, 3, 8, 7, 3]
                                                      c =Counter(l)
                                                      print(c) ## result: {3: 3, 2: 2, 7: 2, 8: 1}





                                                      share|improve this answer

























                                                        up vote
                                                        2
                                                        down vote













                                                        I think you may try collections.Counter, and get different keys and its count in this list.



                                                        from collections import Counter
                                                        l = [2, 3, 7, 2, 3, 8, 7, 3]
                                                        c =Counter(l)
                                                        print(c) ## result: {3: 3, 2: 2, 7: 2, 8: 1}





                                                        share|improve this answer























                                                          up vote
                                                          2
                                                          down vote










                                                          up vote
                                                          2
                                                          down vote









                                                          I think you may try collections.Counter, and get different keys and its count in this list.



                                                          from collections import Counter
                                                          l = [2, 3, 7, 2, 3, 8, 7, 3]
                                                          c =Counter(l)
                                                          print(c) ## result: {3: 3, 2: 2, 7: 2, 8: 1}





                                                          share|improve this answer












                                                          I think you may try collections.Counter, and get different keys and its count in this list.



                                                          from collections import Counter
                                                          l = [2, 3, 7, 2, 3, 8, 7, 3]
                                                          c =Counter(l)
                                                          print(c) ## result: {3: 3, 2: 2, 7: 2, 8: 1}






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Nov 22 at 5:23









                                                          async

                                                          7616




                                                          7616






























                                                              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.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • 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%2f53424276%2fhow-to-group-identical-values-from-a-list-into-their-own-lists%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

                                                              What visual should I use to simply compare current year value vs last year in Power BI desktop

                                                              How to ignore python UserWarning in pytest?

                                                              Alexandru Averescu