Magic Of * In Python

In this article I’ll explain many different ways, we can use * a.k.a. asterisk in Python.

Let’s get started.

Create a Collection With Repeated Elements

Using the * operator we can duplicate the elements as many times as we want. Below is the example code where every element is added 3 times:

lst = [4,3,5] * 3
print(lst)

#output: [4, 3, 5, 4, 3, 5, 4, 3, 5]
Python

This above trick can be applied to tuple as:

lst = (4,3,5) * 3
print(lst)

#output: [4, 3, 5, 4, 3, 5, 4, 3, 5]
Python

We can also generate repeated strings using this:

word = "SH" * 3
print(word)

#output: SHSHSH
Python

Unpacking Function Parameters

Say, a function is defined as shown:

def func(x,y,z):
   print(x,y,z)
Python

Using * we can unpack all the parameters of the function as follows and the good thing is, it will work with lists, tuples as well as with dictionaries.

# list
lst = [0,1,2]
func(*lst)     # output: 0 1 2

# tuple
lst = (0,1,2)
func(*lst)     # output: 0 1 2

# list
dict = {‘x’:1,’y’:2,’z’:3}
func(*lst)     # output: x y z
Python

Unpacking Containers

Let’s consider below sample code:

lst = [1,2,3,4,5]
start, *center, end = lst
print(start)   #output: 1
print(center)  #output: [2, 3, 4]
print(end)     #output: 5
Python

As shown in the above snippet, you can place * in front of any variable and that particular variable will take rest of the values. Let’s take another example:

lst = [1,2,3,4,5]
*start, end = lst
print(start)   #output: [1, 2, 3, 4]
print(end)     #output: 5
Python

args and kwargs

Let’s consider this function definition:

def calculate(a,b,*args,**kwargs):
  print(a)
  for arg in args:
    print(arg)
  for key in kwargs:
    print(key,kwargs[key])
Python

The above defined function calculate(…) holds four parameters, wherein a and b are mandatory parameters and the rest two are positional ones, meaning you can pass any number of arguments there. For more explanation about these, please check out my YouTube, whose link is placed at the end of this article.

Sample values to call this function could be:

calculate(2,3,4,5,6,v1=8,v2=9)

#output:
2
4
5
6
v1 8
v2 9
Python

Merging Different Types Of Iterables

Asterisk can be used to club values from tuple and list as shown below:

var1 = (1,2,3)
var2 = {4,5,6}
lst = [*var1, *var2]
print(lst)

#output: [1, 2, 3, 4, 5, 6]
Python

Merging Two Dictionaries

dict1 = {‘v1’:1,’v2':2}
dict2 = {‘v3’:3,’v4':4}
dict = {**dict1, **dict2}
print(dict)

#output: {'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}
Python

Hope you enjoyed learning about * operator and how we can use this in Python.

If there is anything that is left unclear, I would recommend you to watch my YouTube video as I detailed most of the concepts there with a few more ways to use *.

Up Next
    Ebook Download
    View all
    Learn
    View all