Sep-24-2019, 02:04 PM
Let's explain what different parts are doing and then put them all together:
bool(condition) evaluates whether condition is True or False:
As it was required to have values 10..12 or None depending on condition truthiness list comprehension is used to emit required values, evaluate condition and return corresponding item: 'give me number or None based on whether condition is true or not for every number in range 10..12'
bool(condition) evaluates whether condition is True or False:
>>> condition = '' # empty string (list, tuple, dict etc) is False >>> bool(condition) False >>> condition = 42 >>> bool(condition) TrueIn Python True and False are 1 and 0:
>>> False == 0 True >>> True == 1 TrueSo 'bool(condition)' evaluates and returns False (0) or True (1). This result is used as index:
>>> condition = 42 >>> ['first', 'second'][bool(condition)] 'second' # True is 1 and therefore item at index 1 is returned >>> condition = '' ['first', 'second'][bool(condition)] # False is 0 and item at index 0 is returned 'first'Alternatively it can be expressed this way:
>>> x = 7 < 42 >>> ['first', 'second'][x] 'second' >>> x = 7 > 42 >>> ['first', 'second'][x] 'first'This enables to return either first or second item in list depending whether condition is true or false.
As it was required to have values 10..12 or None depending on condition truthiness list comprehension is used to emit required values, evaluate condition and return corresponding item: 'give me number or None based on whether condition is true or not for every number in range 10..12'
>>> condition = '' >>> [[number, None][bool(condition] for number in range(10, 13)] >>> [10, 11, 12]Returned list is unpacked into variables:
>>> first, second, third = [[number, None][bool(condition)] for number in range(10, 13)] >>> first 10 >>> second 11 >>> third 12
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.