1

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.

lonyen11
  • 91
  • 11

2 Answers2

3

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).

Jan
  • 42,290
  • 8
  • 54
  • 79
  • Thank you. Why did you specify the [0] in the end? – lonyen11 Aug 16 '21 at 20:56
  • @lonyen11: Because this is a list comprehension and you'll get a list with only one element. – Jan Aug 16 '21 at 20:56
  • You might also consider this question: https://stackoverflow.com/questions/10048069/what-is-the-most-pythonic-way-to-pop-a-random-element-from-a-list – Jan Aug 16 '21 at 20:58
  • 2
    A list comprehension is overkill. Just use a ternary with a 2-element list: `other = collection[0] if collection[0] != first else collection[1]` – Woodford Aug 16 '21 at 20:59
  • @Woodford: You're absolutely right. However, list comprehensions are really fast in `Python`. – Jan Aug 16 '21 at 21:01
0

Just shuffle your collection and use the indexes to refer to your first and other variables:

>>> import random
>>> collection = [2, 3]
>>> random.shuffle(collection)
>>> print(f'first={collection[0]}, other={collection[1]}')
first=3, other=2
Woodford
  • 3,746
  • 1
  • 15
  • 29