I have a tuple x = (2,)
to which I would like to append a variable y
. I do not know ahead of time exactly what kind of variable y
will be.
y
could be:
x+y
, orx+(y,)
.Adopting one strategy will give me a TypeError half of the time, and adopting the other will give me (2, (3, 4))
when I want (2, 3, 4)
.
What's the best way to handle this?
To concatenate two tuples we will use ” + ” operator to concatenate in python. This is how we can concatenate two tuples in Python.
Existing tuples can be concatenated or multiplied to form new tuples through using the + and * operators.
Why do Python lists let you += a tuple, when you can't + a tuple? In other words: No. Trying to add a list and a tuple, even if we're not affecting either, results in the above error. That's right: Adding a list to a tuple with + doesn't work.
You can use + operator to concatenate two or more tuples.
Use the second strategy, just check whether you're adding an iterable with multiple items or a single item.
You can see if an object is an iterable (tuple
, list
, etc.) by checking for the presence of an __iter__
attribute. For example:
# Checks whether the object is iterable, like a tuple or list, but not a string.
if hasattr(y, "__iter__"):
x += tuple(y)
# Otherwise, it must be a "single object" as you describe it.
else:
x += (y,)
Try this. This snippet will behave exactly like you describe in your question.
Note that in Python 3, strings have an __iter__
method. In Python 2.7:
>>> hasattr("abc", "__iter__")
False
In Python 3+:
>>> hasattr("abc","__iter__")
True
If you are on Python 3, which you didn't mention in your question, replace hasattr(y, "__iter__")
with hasattr(y, "__iter__") and not isinstance(y, str)
. This will still account for either tuples or lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With