Statement for 2 arguments, how does it work?

Asked

Viewed 186 times

-2

I saw this statement in a code on codewars and I couldn’t understand how it works:

def multiple_of_index(arr):
    return [val for index, val in enumerate(arr) if index and val % index == 0]

enumarate(arr) creates a list of tuples containing the index and value similar to a type variable dictionary right?

In this case, the declaration for will iterate through the list of tuples generated by enumarate twice? Once for the argument index and another for the argument val?

And as the statement if will it work? The statement for will iterate only if the declaration if return true?

1 answer

1


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.