Python's star (*) operator is a built-in operator with different functionalities. How this operator works depends on its utilization in the development environment.
Let's take a look at those functionalities in detail.
There are three primary meanings/functionalities that this operator provides:
For numeric operations, the application of the star (*) operator multiplies two integers:
#integer multiplicationnum1 = 5num2 = 10print(num1 * num2)#decimal multiplicationnum3 = 3.5num4 = 6.5print(num3 * num4)#complex number multiplicationa = complex(2,3)b = complex(3,6)print(a*b)
The above code snippet shows that the star (*) operator applies the mathematical multiplication function to different numerical data types and caters to complex data types.
The star (*) operator in Python functions allows passing a non-finite number of parameters:
def printResult(*params):for i in params:print(i)printResult(5,10,15,20,25,30)
The printResult()
function in the code uses the star (*) operator to receive an unrestricted number of arguments. Similarly, we can pass an extensive series of parameters in a function using this operator without actually typing them in the function declaration statement.
The star (*) operator allows repetition in Python. Sequences of strings, lists, tuples, and more can be repeated using this operator:
#string repetitionmessage = "Hello World! "print(message * 5)#python list repetitionnumberlist =[1,2,3]print(numberlist * 3)#python tuple repetitionfruits = ("orange", "mango", "pineapple")print(fruits * 2)
Strings, lists, and tuples can all be repeated using the star (*) operator in Python, making coding sequences easier to write and print.
The star (*) operator is one of the fundamental operators of Python. It is integral for multiplicative solutions. It is a smart alternative to loops that need to traverse a list or a tuple multiple times and functions that need multiple argument definitions.
Free Resources