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
listis a keywordlistis not a keywordiis being iterated over all element indices, so when it's on the last element,i+1will be out of bounds. But a bigger problem is that you're only checking adjacent elements for duplicates. What if your list is[1, 2, 1]? Your algorithm will return all three elements, which I don't believe you want.