def multiple_of_index(arr):
return [val for index, val in enumerate(arr) if index and val % index == 0]
The parameter arr
will be of an eternal type. The function enumerate
will go through the values of arr
and generate a tuple of two values: the first value will be the position of the iterated value within the original object and the second value will be the value present in the iterated object.
Imagining a list ['a', 'b', 'c']
, the enumerate
would generate pairs of values: (0, 'a')
, (1, 'b')
and (2, 'c')
. Note that I always say "generate", because the return of the function is a generator - one of the eternal types of Python characteristic for effecting the Lazy-Evaluation.
Through the deconstruction of tuples, the pair of values generated by enumerate
shall be assigned to the variables index
and val
in the stretch index, val in enumerate(arr)
.
From this is built an understanding of list (comprehensilist on) containing the value of val
when the condition is met. In this case the condition is if index and val % index == 0
, that is, if index
is assessed as true and val
is multiple of index
. The value of index
will only be evaluated as false when value 0, so the condition will be if index
is different from 0 and val
is multiple of index
. When the condition is met the value of val
will enter the final list, being returned from the function.
The equivalent code is:
def multiple_of_index(arr):
result = []
index = 0
for val in arr:
if index != 0 and val % index == 0:
result.append(val)
index += 1
return result
Related:
Thank you very much for the detail, I was able to understand the logic of the expression
– Tantalus