---title: "Using Iterable Unpacking for Literals as List Concatenation in Python"author: "Andres Monge <aemonge>"date: "2024-12-20"format: html: smooth-scroll: true code-fold: true code-tools: true code-copy: true code-annotations: true---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 ExampleGiven the original code snippet:```{python}from typing import Literal, get_argsmy_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 thestructure. For example:```{python}nested_list = [[1, 2], [3, 4]]flattened_list = [*nested_list]print(flattened_list) # Output: [[1, 2], [3, 4]]```#### Combining with Other IterablesYou can also use iterable unpacking with other iterable objects like tuples orsets:```{python}tuple_1 = (1, 2, 3)set_1 = {4, 5}combined_iterable = [*tuple_1, *set_1]print(combined_iterable) # Output: [1, 2, 3, 4, 5]```