Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate tuple with variable

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:

  • a tuple, in which case I'm quite happy to use x+y, or
  • a single object (typically string or int), in which case I should use x+(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?

like image 699
Qi Chen Avatar asked Mar 27 '16 13:03

Qi Chen


People also ask

How do you concatenate values in a tuple?

To concatenate two tuples we will use ” + ” operator to concatenate in python. This is how we can concatenate two tuples in Python.

Can you concatenate a tuple?

Existing tuples can be concatenated or multiplied to form new tuples through using the + and * operators.

Can you use += with tuple?

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.

How can you concatenate two tuples with example?

You can use + operator to concatenate two or more tuples.


1 Answers

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.

like image 193
Luke Taylor Avatar answered Sep 19 '22 16:09

Luke Taylor