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:
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.
Luke taylor
source share