Variable Concatenate Tuple

I have a tuple x = (2,) to which I would like to add the variable y . I do not know in advance which variable y will be.

y may be:

  • tuple, in which case I am very happy to use x+y or
  • one object (usually a string or int), in which case I have to use x+(y,) .

Adopting one strategy will give me half the TypeError time and the other will give me (2, (3, 4)) when I want (2, 3, 4) .

What is the best way to handle this?

+7
python concatenation tuples
source share
2 answers

Use isinstance in an if state.

 >>> x = (2,) >>> y1 = (1,2) >>> y2 = 2 >>> def concat_tups(x,y): ... return x + (y if isinstance(y,tuple) else (y,)) ... >>> concat_tups(x,y2) (2, 2) >>> concat_tups(x,y1) (2, 1, 2) >>> 
+1
source share

Use the second strategy, just check if you are adding an iteration with multiple elements or one element.

You can see if the object is iterable ( tuple , list , etc.) by checking for the presence of the __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 it. This snippet will behave exactly as you describe in your question.

Note that in Python 3, strings have a __iter__ method. In Python 2.7:

 >>> hasattr("abc", "__iter__") False 

In Python 3+:

 >>> hasattr("abc","__iter__") True 

If you're on Python 3 that you didn't mention in your question, replace hasattr(y, "__iter__") with hasattr(y, "__iter__") and not isinstance(y, str) . This will still take into account either tuples or lists.

+4
source share

All Articles