
When working with existing tuples, sometimes we want to create new tuples that contain all the elements in the existing tuples. In this case, we can use an asterisk that precedes the tuple, which will unpack all the items in the tuple.
The following code shows you such an example:
- By placing the asterisk before
grouping_factors1
, we’re able to unpack all of its items. - The printout of
grouping_factors
reveals this fact. - It should be noted that this syntax (i.e. starred expression) can’t be used by itself, as shown below:
>>> *grouping_factors1
File "<input>", line 1
SyntaxError: can't use starred expression here
- Instead, it has to be used as part of other expressions. In addition to the example shown above, we can use it to create a copy of the tuple by using the following code. The comma after the starred expression is significant because it makes the entire expression of creating a tuple object.
>>> *grouping_factors1,
('country', 'state')
- More broadly, we should know that the starred expression is used with any iterable to get all individual items. Tuples are just one kind of iterable among others, such as lists and strings. The following code shows you some relevant examples:
>>> *"HI", "T"
('H', 'I', 'T')
>>> *[1, 2, 3], 4
(1, 2, 3, 4)