-3

I am looking for a single set operation to accomplish both the cases below. Is there a way to do this python?

Case 1:
a = set([1,2]) and b = set([1,2,3])
I want a result [1,2], which is a straightforward intersection. Now set(a) could be empty and performing intersection on empty set with any other set would lead to empty set.

Case 2:
a = set([]) and b = set([1,2,3]) => set([1,2,3]) i.e. set b

How can I achieve case 1 and case 2 with one set operation.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Program Questions
  • 440
  • 2
  • 6
  • 20

2 Answers2

3

If what you want is "if a is non-empty, give me the intersection; otherwise just give me b", then what you want is:

result = (a&b) if a else b

"I don't want to use if conditional to check its value" does not make much sense as a requirement. This is what if is for: varying behaviour based on some condition.

khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Use and and or, which will short-circuit to produce the desired results:

>>> a = {1,2}
>>> b = {1,2,3}
>>> a and a&b or b
{1, 2}
>>> a = {}
>>> b = {1,2,3}
>>> a and a&b or b
{1, 2, 3}
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97