python – Add Variables to Tuple
python – Add Variables to Tuple
Tuples are immutable; you cant change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:
a = (1, 2, 3)
b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
c = b[1:] # (2, 3, 4, 5, 6)
And, of course, build them from existing values:
name = Joe
age = 40
location = New York
joe = (name, age, location)
You can start with a blank tuple with something like t = ()
. You can add with +
, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,)
. You can add a tuple of multiple elements with or without that trailing comma.
>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)
python – Add Variables to Tuple
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 its natural to implement BUILD_TUPLE_UNPACK
faster than BINARY_ADD
because BINARY_ADD
is a polymorphic operator, requiring additional type calculation and implicit conversion.