Python not support adding a tuple to a list:
>>> [1,2,3] + (4,5,6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
What are the disadvantages for providing such a support in the language? Note that I would expect this to be symmetric: [1, 2] + (3, 4)
and (1, 2) + [3, 4]
would both evaluate to a brand-new list [1, 2, 3, 4]
. My rationale is that once someone applied operator + to a mix of tuples and lists, they are likely to do it again (very possibly in the same expression), so we might as well provide the list to avoid extra conversions.
Here's my motivation for this question.
It happens quite often that I have small collections that I prefer to store as tuples to avoid accidental modification and to help performance. I then need to combine such tuples with lists, and having to convert each of them to list makes for very ugly code.
Note that +=
or extend
may work in simple cases. But in general, when I have an expression
columns = default_columns + columns_from_user + calculated_columns
I don't know which of these are tuples and which are lists. So I either have to convert everything to lists:
columns = list(default_columns) + list(columns_from_user) + list(calculated_columns)
Or use itertools:
columns = list(itertools.chain(default_columns, columns_from_user, calculated_columns))
Both of these solutions are uglier than a simple sum; and the chain
may also be slower (since it must iterate through the inputs an element at a time).