In Python 3, you can use *
to create a new tuple of elements from the original tuple along with the new element.
>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')
The byte code is almost the same as tuple1 + ("baz",)
Python 3.7.5 (default, Oct 22 2019, 10:35:10)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... tuple1 = ("foo", "bar")
... tuple2 = (*tuple1, "baz")
... return tuple2
...
>>> def g():
... tuple1 = ("foo", "bar")
... tuple2 = tuple1 + ("baz",)
... return tuple2
...
>>> from dis import dis
>>> dis(f)
2 0 LOAD_CONST 1 (('foo', 'bar'))
2 STORE_FAST 0 (tuple1)
3 4 LOAD_FAST 0 (tuple1)
6 LOAD_CONST 3 (('baz',))
8 BUILD_TUPLE_UNPACK 2
10 STORE_FAST 1 (tuple2)
4 12 LOAD_FAST 1 (tuple2)
14 RETURN_VALUE
>>> dis(g)
2 0 LOAD_CONST 1 (('foo', 'bar'))
2 STORE_FAST 0 (tuple1)
3 4 LOAD_FAST 0 (tuple1)
6 LOAD_CONST 2 (('baz',))
8 BINARY_ADD
10 STORE_FAST 1 (tuple2)
4 12 LOAD_FAST 1 (tuple2)
14 RETURN_VALUE
The only difference is BUILD_TUPLE_UNPACK
vs BINARY_ADD
. The exact performance depends on the Python interpreter implementation, but it's natural to implement BUILD_TUPLE_UNPACK
faster than BINARY_ADD
because BINARY_ADD
is a polymorphic operator, requiring additional type calculation and implicit conversion.