Home > Net >  Remove duplicate from list without using another list or set
Remove duplicate from list without using another list or set

Time:12-29

Want to remove duplicate in the python list, just want to keep unique values

l=[3,2,3,4,5,6,1,2]

for i in range(len(l)):
    if i in l[:i 1]:
        l.pop(i-2)

If am puting pop(i).... it is giving pop out of range

while moving forward in through loop in list, am trying to check if they are present in previous part l[0:i 1], if it's present pop the current item.


Don't wan't to use set!!!

CodePudding user response:

You can use this method by converting the list into the set and then converting it into the list again.

The set data structure contains only unique elements so by converting the into the set we are eliminating all the duplicate elements but the data type will be set. So to get the original data type we need to convert the set to a list again. Now we have a list without any duplicate elements.

l=[3,2,3,4,5,6,1,2]
list(set(l))

Output

[1, 2, 3, 4, 5, 6]

CodePudding user response:

Since you've mentioned not to use any other data structure, I am providing a solution that runs in quadratic time with respect to the length of the list.

l = [3, 2, 3, 4, 5, 6, 1, 2]
for i in range(len(l)):
    for j in range(len(l) - 1, i, -1):
        if l[i] == l[j]:
            l.pop(j)

print(l)

How it works:

The outer loop with variable i is used to iterate over the list. The nested loop with variable j is used to check if the item is present in the slice after the index i. Every such index is discarded.

Note that we are iterating backwards in the nested loop to avoid index out-of-range situations.

This implementation will not alter the order of the elements and doesn't use any extra space.

CodePudding user response:

l=[3,2,3,4,5,6,1,2]

loc = 0
while loc < len(l):
    # test if the item in the current position already exists in l[:loc]
    if l[loc] in l[:loc]:
        # remove the current item
        l.pop(loc)
    else:
        # move the loc variable to test the next item
        loc  = 1
    # if we removed an item we test the new item that gets pushed into this position

print(l)
# [3, 2, 4, 5, 6, 1]

CodePudding user response:

If we typecast a list into set then also we can remove duplicates example:

x= [1,1,2,1,2,1,3,4]

here x is a list which contains duplicates

y = set(x)
print(y)

output - {1,2,3,4}

So, in this example when I type casted x to set and stored output in y , then y as a set contains only unique elements

Also if we want to convert this set back to list then we can do this:

z= list(y)
  • Related