[Tutor] Clubbing simillar elements together in a list with repeating elements

Hugo Arts hugo.yoshi at gmail.com
Thu Feb 24 13:03:26 CET 2011


Won't give you all the ansers, but here's a few tips.

On Thu, Feb 24, 2011 at 12:29 PM, ranjan das <ranjand2005 at gmail.com> wrote:
>
> I have a list
>
> a=[1,2,3,4,2,5,5,4,6,7,8]
>
> I want to club the repeating elements together and my output should be
> something like
>
> a_new=[ [1], [2,2], [3], [4,4] , [5,5,5],[6], [7], [8]]
>

In you original list a, there's only 2 fives. Please make sure that
you type everything in accurately, and use the same example
throughout, or we get confused far more easily.

> How do I do this?
>
> I tried the following but it is not giving me the desired result
>
>
> for element in Unique:
>     if element in Duplicate:
>         count=0
>         for i in Duplicate:
>             if i==element:
>                 count=count+1
>
>         for j in range(count+1):
>             FinList.append(element)
>     else:
>         FinList.append([element])
>

The mistake is in that piece. Note that if the element is not in
duplicate, you append it *inside* a separate list. But if it *is* in
duplicate, you append all the elements to FinList directly, *without*
creating a separate list for them. Note that you don't have to use the
range() function. Try this in the interpreter:

>>> [5] * 3
[5, 5, 5]

Can you use that neat little multiply trick to avoid having to loop
over a range?

This problem has come up before, and you can do it much, much quicker.
You can create the Unique list much easier by simply using the set()
function. Then, the count() method counts how often an item appears in
a list.

Finally, we can make it even shorter with the groupby function from
the itertools package, which was pretty much made for this:

HTH,
Hugo


More information about the Tutor mailing list