I have a code listed below that accepts a list and then returns a new list with every second value removed.
Can someone explain to me how this code works? I understand that the enumerate function will put the list into a list of tuples. Example: [1,2,3,4,5] will go to (0,1) (1,2) (2,3) (3,4) (4,5)
Question 1: In the code why is "val" listed before the for loop in the return statement and then listed a second time after the for?
Question 2: After the word "for" is i for index 0 of the resulting tuple from the enumerate?
Question 3: After the word "for" is val for index 1 of the resulting tuple from the enumerate?
CODE:
def remove_every_other(lst):
return [val for i,val in enumerate(lst) if i % 2 == 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]
Regarding Q1, this is just a list comprehension syntax. In your function it creates a list and returns it. It could be rewritten as a regular for loop, e.g.
def remove_every_other(lst):
result = []
for i, val in enumerate(lst):
if i % 2 == 0:
result.append(val)
return result
In Python list comprehension is a more natural way to do this same thing.
Answers to Q2 & Q3 are yes and yes.
I think the function would be easier to understand if it looked something like this
def remove_every_other(lst):
return [i for i in lst if i % 2 != 0]
print(remove_every_other([1,2,3,4,5])) # [1,3,5]