Search code examples
pythonfor-loopindexingenumerate

For loop with enumerate - index position


I have a solution to erase duplicates from a list. In this solution is used an enumerate.

def myfunc(list_input):
    list_output=[]
    for num1, num2 in enumerate(list_input):
        if num2 not in list_input[0:num1]:
            list_output.append(num2)
    return list_output

print(myfunc([1,1,2,3])) --> ,[1,2,3,]

However, I do not undersatand in which way we should read the index position for our enumerate.

What is the position for each interaction in list_input[0:num1], having in consideration that we have started the for loop with a num1, num2?


Solution

  • Enumerate iterates over an iterable (in this cause list_input), and with each iteration sets the first value (in this case num1) to the current index, and the second value (in this case num2) to the value of the iterable at this index.

    For example, on first iteration, num1 == 0 as the iteration begins at the zeroeth element, and num2 == 1 as list_input[0] == 1. list_input[0:num1] == [] so nothing is in it and therefore the value is appended to the outputs.

    On second iteration, the index has incremented by one and so num1 == 1. list_input[0:num1] == [1] now, and as num2 is in [1], the value is not appended to the output list.