Creating A List of Unique Elements(Problem)

I tried creating a list of unique elements,which came to be a set of unique elements for each step i performed the for loop.The main goal is the commented statement on the top of the algorithm,that says " # the answer is: [‘c’, ‘a’, ‘t’, ‘d’, ‘o’, ‘g’, ‘r’, ‘b’, ‘i’] ".This is a list of unique elements which I want to achieve.Finally pushing all the elements into unique_list List object.

# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
list_ = ['c','c','c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
#print(len(list_))
unique_list_obj = []
count_list = []
def unique_list(list_obj,start):
    #print(len(list_obj))
    present = False
    for i in range(0,len(list_obj),2):
        #print(i)
        start += 2
        if start < len(list_obj):
            #print(i,start)
            if list_obj[i] == list_obj[start]:
                present = False
                print(list_obj[i],list_obj[start])
                print('------------------------------------')
            else:
                present = True
                print(list_obj[i],list_obj[start])

    return unique_list_obj

print(unique_list(list_,1))

Unique elements are missing and some repeated elements are still present.Try modifying this algorithm.

You can create a set from the list and it’ll remove the duplicates but order won’t be maintained tho but you’ll get unique elements only.

data = [1, 1, 1, 2, 3, 3]
result = list(set(data))

Now, if you want to maintain an order then you can create an extra list to keep track of unique elements.

data = [1, 1, 1, 2, 4, 3, 4, 5, 4]
result = []
for i in data:
    if i not in result:
        result.append(i)
print(result) # unique elements
1 Like

Thanks,I always try to make algorithms complicated,I didn’t get the idea of your second solution.

Let me explain my second approach.

  1. Input is stored in data, which may or may not contain duplicates.

  2. result is going to store distict elements. We’ll see how in next steps.

  1. Now comes the loop which goes through data and checks if i (which is the current element of iteration), is present in the result list or not. If it’s not then add i to the result.

That’s it.

Hope it helps.