Append duplicate items at the end of list whithout changing the order
<p>I am new to python and was trying to Append duplicate items at the end of list whithout changing the order</p>

<pre><code>testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(alist):
    p = len(alist)
    duplicate = False
    for i in range(0, p):
        for j in range (i + 1, p):
            if alist[i] == alist[j]:
                b = alist.index(alist[j])
                a = alist.pop(b)
                alist.append(a)
                p -= 1
                duplicate = True

    print alist

if duplicate == False:
    print "No duplicate item found"

duplicate(testlist)
</code></pre>

<p>OUTPUT : <code>[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]</code></p>

<p>DESIRED OUTPUT : <code>[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]</code></p>

<p>Any help what wrong I am doing here</p>

<p>You may use the Collections module to get <code>OrderedDict</code> for maintaining the order of elements.</p>

<p>The technique we use here is to create a dictionary to store the number of occurrences of each element in the array and use the <code>dict</code> to lookup the number of occurrences for later use.</p>

<p>In the <code>for</code> loop we look up if there is already element present in the <code>dict</code> using the <code>get</code> method. If <code>true</code> then we increase the counter else initialize the counter to be zero.</p>

<pre><code>import collections
lst = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

# Create a dictionary storing the the number of occurences
occurences_dict = collections.OrderedDict()
for i in lst:
    occurences_dict[i] = occurences_dict.get(i, 0) + 1

final = occurences_dict.keys() + [k for k, v in occurences_dict.items() if v&gt;1]

print final
&gt;&gt;&gt; [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]
</code></pre>

python python-2.7 scripting