Member-only story
Magic Of * In Python
In this article I’ll explain about many different ways, we can use * a.k.a. asterisk in Python.
Let’s get started.
Create Collection With Repeated Elements
Using * 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]
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]
We can also generate repeated strings using this:
word = "SH" * 3
print(word)#output: SHSHSH
Unpacking Function Parameters
Say, a function is defined as shown:
def func(x,y,z):
print(x,y,z)
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 =…