Answer the question
In order to leave comments, you need to log in
I can't understand how the code works (tuple, dictionary, lambda)?
Good day.
I came across the following code and I can't understand how it works (the output of all three prints is exactly the same).
In particular, I can’t understand how, as I understand it, a list of one element (boolean) and three different data types (tuple, dictionary, lambda functions) interacts with each other.
Especially the last construction is not clear to me, since the functions themselves are not described in it.
The code:
a = 10
b = 20
print("Minimal is", (b, a) [a<b]) # Minimal is 10
print("Minimal is", {True: a, False: b} [a<b]) # Minimal is 10
print("Minimal is", (lambda: b, lambda: a) [a<b]()) # Minimal is 10
Answer the question
In order to leave comments, you need to log in
[a<b]
implicitly cast to int. True - 1, False - 0.
In the first case, everything is simple - either 0 or 1 element is taken.
In the second case, it [a<b]
returns either True or False, and the value by key is returned from the dictionary.
The third one has a tuple of 2 lambda functions. 1st returns b, 2nd - a, and the desired function is selected as in the first case
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question