I have a collection of two variables
a = 2
b = 3
collection = [a, b]
I randomly choose one of them as my first variable:
first_variable = random.choice(collection)
Later, I want to select the other variable and store it in other_variable
.
How can I do this only by referring to first_variable
and collection
?
other_variable = something like "variable in collection
that is not first_variable
"
Remark: The collection will always contain two elements only. Thank you.
Straight-forward:
a = 2
b = 3
collection = [a, b]
import random
first_variable = random.choice(collection)
other_variable = [item for item in collection if item != first_variable][0]
print(other_variable)
Caution: this will obviously fail if a == b
(it will produce an IndexError
).