What does an expression between parentheses mean followed by an expression between brackets?

Asked

Viewed 67 times

-1

I found this code:

nums = [1,2,3,4,5,6,7,8]
round(sum(a ** (2, 0.5)[a % 2] for a in nums), 2)

My doubt is in this passage (2, 0.5)[a % 2], what name? How it works?

1 answer

4


Let’s go in pieces...

(2, 0.5) is a tuple containing two numbers: the 2 and the 0.5.

In a tuple, we can access its elements separately, through its indices, the first index being zero, the second is 1, etc. Example:

# tupla contendo dois números
expoentes = (2, 0.5)

# acessando os elementos da tupla pelo índice
print(expoentes[0]) # 2
print(expoentes[1]) # 0.5

But nothing stops you from doing that:

print((2, 0.5)[0]) # 2
print((2, 0.5)[1]) # 0.5

That is, I create the tuple (without assigning it to a variable) and already access directly one of its indexes.


In the case of your code, the index is a % 2: the rest of the a by 2. When dividing a number by 2, the rest shall be 0 (when the number is even) or 1 (when the number is odd), and this result is being used as the index of the tuple.

So a ** (2, 0.5)[a % 2] is making a squared or 0.5 (which is the same as "the square root of a"). When a is even, the result of a % 2 is zero, and therefore it takes the first element of the tuple (the 2). If a be odd, a % 2 is 1, and so he takes the second element of the tuple (0.5).

So the expression elevates a squared when a is even, and raises a to 0.5 when a is odd. It does this for each number in the list nums, sum the results and then round to 2 decimal places (the call to round).

So it’s the same as that:

nums = [1,2,3,4,5,6,7,8]
expoentes = (2, 0.5)
total = 0
for a in nums:
    indice = a % 2
    total += a ** expoentes[indice]
print(round(total, 2))

But it was done in a row, "saving" variables and using a Generator Expression.

  • Thank you very much!! Excellent explanation.

Browser other questions tagged

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