Have you tried the unpack operator in python?

Originally posted on dev.

The one thing, which I love in Python is its unpack operator (* and **). This operator can be used with any iterable(list, dictionary, tuple, etc). It makes the code very elegant, adds performance to the code and I can do a ton of things using it.

Here are some of my use cases for the unpack operator-

1. Pass function parameters-

Often times, it happens that, the function has too much parameters with long names, and passing each value to parameter makes the code harder to read.

To tackle this problem you can use unpack operator(* if there are positional arguments or ** if there are keyword arguments)


def my_func1(*args, **kwargs):
  args is a tuple, so you can use indexing to get the values
  kwargs is a dict, so you can use, kwargs.get(param_name) to access the value

positional_args = (1, 2, 3, 4)
keyword_args = { 'arg1': 1, 'arg2': 2, 'arg3': 3 }

my_func1(*positional_args, **keyword_args)

In this way you can make your code more readable, and if the values for the function are static then, you can import them from a seperate file.

2. Update list or dictionary-

Using Unpack operator we can update a list or dict without using any inbuilt function

list1 = [1, 2, 3]
dict1 = {'a': 1, 'b': 2}

# add a new element
list1 = [*list1, 10]
dict1 = {**dict1, 'c': 3}

print(list1, dict1)

3. Merge a list or dictionary-

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list3 = [*list1, *list2]

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'c': 4}

dict3 = {**dict1, **dict2}

4. Split an iterable into multiple parts

my_string = "hello devs!"

sub_str1, *sub_str2 = my_string

Source: dev