Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find unique elements in a list in python? (Without using set)

Write a function that accepts an input list and returns a new list which contains only the unique elements (Elements should only appear one time in the list and the order of the elements must be preserved as the original list. ).

def unique_elements (list):
    new_list = []
    length = len(list)
    i = 0
    while (length != 0):
        if (list[i] != list [i + 1]):
            new_list.append(list[i])
        i = i + 1
        length = length - 1
    '''new_list = set(list)'''
    return (new_list)

#Main program
n = int(input("Enter length of the list: "))
list = []
for i in range (0, n):
    item = int(input("Enter only integer values: "))
    list.append(item)
print ("This is your list: ", list)
result = unique_elements (list)
print (result)

I am stuck with this error:

IndexError: list index out of range

like image 222
Karan Thakkar Avatar asked Feb 21 '16 07:02

Karan Thakkar


3 Answers

This is the simplest way to do it:

a = [1, 2, 2, 3]
b = []
for i in a:
    if i not in b:
        b.append(i)
print (b)
[1, 2, 3]
like image 137
Joe T. Boka Avatar answered Oct 16 '22 15:10

Joe T. Boka


The problem with your code is that you are looping length times but checking list[i] with list[i+1], thus accessing an element past the end of the input list (e.g. in a list with 6 elements there are 6-1=5 pairs of consecutive elements).

A second issue with your code is that an input with only one element [1] should give as output [1] even if this element is not different from any other. The input text means you should remove elements that are equal to other elements already present, not that you should keep elements that are different from the next one.

Another issue is that you're only checking for consecutive duplicates i.e. given the input list [1, 2, 1, 2] your logic wouldn't detect any duplication... looks like the exercise instead requires in this case as output of [1, 2].

A trace for a simple algorithm to do this is

for each element in input
   if the element has not been included in output
       add the element to the end of output

Note also that to check if an element is present in a list Python provides the in operator (e.g. if x in output: ...) that can save you an explicit loop for that part.

As a side note naming an input parameter list is considered bad practice in Python because list is the name of a predefined function and your parameter is hiding it.

like image 3
6502 Avatar answered Oct 16 '22 16:10

6502


O(n) solution without using a set:

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict):
...     pass
... 
>>> lst = [1, 2, 2, 3, 4, 5, 4]
>>> [x for x,c in OrderedCounter(lst).items() if c==1]
[1, 3, 5]
like image 2
timgeb Avatar answered Oct 16 '22 14:10

timgeb