Roman Rdgz
Roman Rdgz

Reputation: 13264

Join two elements as a tuple, which can be a tuple themselved or not

Strange title, but easy to ask with an example:

mytuple = (1, 2)
mynumber = 3
print (mynumber,) + (mytuple,)
>> (3, (1, 2))

I don't want a tuple inside a tuple. I expect getting (3, 1, 2). Any idea?

Upvotes: 0

Views: 45

Answers (3)

vks
vks

Reputation: 67988

mytuple = (1, 2)
mynumber = 3
print (mynumber,)+mytuple

Upvotes: 0

njzk2
njzk2

Reputation: 39406

you can use a lambda to get tuple out of anything:

always_tuple = lambda x: x if isinstance(x, tuple) else (x,)

joined = always_tuple(a) + always_tuple(b)

Upvotes: 0

Piotr Dabkowski
Piotr Dabkowski

Reputation: 5939

You have to check whether second object is a tuple:

a = (1, 2)
b = 3
joined = (a if isinstance(a, tuple) else (a,)) + (b if isinstance(b, tuple) else (b,))

Upvotes: 1

Related Questions