Using Iterable Unpacking for Literals as List Concatenation in Python

Author

Andres Monge

Published

December 20, 2024

Iterable unpacking is a powerful feature in Python that allows you to concatenate lists in a concise and efficient manner.

This method leverages the * operator to unpack the elements of multiple lists into a single list.

Practical Example

Given the original code snippet:

Code
from typing import Literal, get_args

my_literal = Literal["hello", "world"]

without_unpacking = list(get_args(my_literal)) + ["foo"] # ["hello", "world", "foo"]
with_unpacking = [*get_args(my_literal), "foo"]          # ["hello", "world", "foo"]
assert without_unpacking == with_unpacking

Additional Tips

Handling Nested Lists

The * operator can handle nested lists by unpacking their elements and flattening the structure. For example:

Code
nested_list = [[1, 2], [3, 4]]
flattened_list = [*nested_list]
print(flattened_list)  # Output: [[1, 2], [3, 4]]
[[1, 2], [3, 4]]

Combining with Other Iterables

You can also use iterable unpacking with other iterable objects like tuples or sets:

Code
tuple_1 = (1, 2, 3)
set_1 = {4, 5}
combined_iterable = [*tuple_1, *set_1]
print(combined_iterable)  # Output: [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]