Reputation: 1488
In Python, what is a simple way to always return a tuple whether the variable in question holds a tuple or a list containing at least one tuple?
# (3, 5) would return (3, 5)
#
# [(3, 5), [200, 100, 100]] would return (3, 5)
#
# [[100, 100, 100], (3, 5)] would return (3, 5)
#
# [(3, 5), (4, 7)] would return (3, 5)
Upvotes: 0
Views: 55
Reputation: 310059
If I actually needed something like this, I would do something like:
def first_tuple(t):
return t if isinstance(t,tuple) else next(x for x in t if isinstance(x,tuple))
demo:
>>> first_tuple((3,5))
(3, 5)
>>> first_tuple([(3, 5), [200, 100, 100]])
(3, 5)
>>> first_tuple([[100, 100, 100], (3, 5)])
(3, 5)
>>> first_tuple([(3, 5), (4, 7)])
(3, 5)
>>> first_tuple([[],[]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in first_tuple
StopIteration
Generally speaking, you shouldn't need something like this. IMHO, this seems like it is probably a poor design and the data-structure here should be reconsidered.
Upvotes: 3