Remove_duplicates


#1

def remove_duplicates(inputlist):
if inputlist == []:
return []

Sort the input list from low to high

inputlist = sorted(inputlist)

Initialize the output list, and give it the first value of the now-sorted input list

outputlist = [inputlist[0]]

Go through the values of the sorted list and append to the output list

…any values that are greater than the last value of the output list

for i in inputlist:
    if i > outputlist**[-1]:**
        outputlist.append(i)
    
return outputlist

What does the -1 do/mean(see third to last line of code)? Thanks.


#3

we can access lists by index, using negative indexes means we can access the list from the right hand side, so -1 as index will retrieve the last item from the list. -2 will get you the before last item in a list and so on:

h   e   l   l   o
0   1   2   3   4
-5  -4  -3  -2  -1 

we can use positive values (left hand side) and negative values (from the right hand side of string or list)


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.