Append duplicate items at the end of list whithout changing the order

Question:

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

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)

OUTPUT : [32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]

DESIRED OUTPUT : [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]

Any help what wrong I am doing here

Asked By: Aniket

||

Answers:

I think that in this case the creation of a new list is more efficient and clear in comparison with the permutations in the original list:

testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(alist):

    filtered, duplicates = [], []
    for element in alist:
        if element in filtered:
            duplicates.append(element)
            continue
        filtered.append(element)

    if not duplicates:
        print "No duplicate item found"
        return alist
    return filtered + duplicates

new_list = duplicate(testlist)
print new_list
Answered By: ShabashP

You may use the Collections module to get OrderedDict for maintaining the order of elements.

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 dict to lookup the number of occurrences for later use.

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

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>1]

print final
>>> [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]
Answered By: ZdaR

I solved it this way. I also made some changes to make the code a bit more Pythonic.

test_list = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(a_list):
    list_length = len(a_list)
    duplicate = False
    checked = []
    for i in range(list_length):
        if a_list.count(a_list[i]) > 1:
            if a_list[i] not in checked:
                duplicate = True
                a_list.append(a_list[i])
                checked.append(a_list[i])
    if duplicate == False:
        print("No duplicate item found")
        return None
    return a_list

print(duplicate(test_list))
Answered By: coralvanda

Instead of checking values, compare on index.

Please check this code:

testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56,32]

print("Original list - ",testlist)
tmp_list = []
exclude =[]
for i in range(len(testlist)):
    if i == testlist.index(testlist[i]):

        tmp_list.append(testlist[i])
    else:
        exclude.append(testlist[i])
tmp_list.extend(exclude)
testlist = tmp_list

print("Updated list - ",testlist)

Output:

C:Usersdinesh_pundkarDesktop>python c.py
Original list -  [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56, 32]
Updated list -  [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2, 32]

C:Usersdinesh_pundkarDesktop>
Answered By: Dinesh Pundkar

I have developed a algo which extends the duplicates in such a way that if duplicate contains duplicate we are extends them to end also

eg – input – [1,1,2,2,3,3,4,5,2,5]
output – [1, 2, 3, 4, 5, 2, 3, 2] – (Solution 2)

others ouput – [1, 2, 3, 4, 5, 2, 2, 3] where 2 repeats (Solution 1)

Solution 1 –

def remove_extend(l):
    stack = []
    duplicates = []

    for i in l:
        if i not in stack:
            stack.append(i)
        elif i in stack:
            duplicates.append(i)
    
    stack.extend(duplicates)

    return stack

l =  [1,2,2,2,3,3,4,5]
ans = remove_extend(l)
print(l)
print(ans)

Solution 2

def check_dict(d):
    if d == {}:
        return False
    # stack = []
    for k,v in d.items():
        
        if v == 0:
            del d[k]
        
        return True

def add_to_stack(stack, d):
    for k,v in d.items():
           
            if v>=1:
                stack.append(k)
                d[k] -= 1
    return [stack,d]      


def duplicates_extend2(ls):
    d = {}
    stack = []
    for i in ls:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1


    print(d)
    if_dict = check_dict(d)
    while if_dict:
        ans  = add_to_stack(stack, d)
        stack = ans[0]
        d = ans[1]
        if_dict = check_dict(d)
        

    return stack


ls = [1,1,2,2,3,3,4,5,2,5]
ans = duplicates_extend2(ls)
print(ans)
Answered By: Pratik Patil
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.