What does the Star operator mean in Python?


The asterisk (*) operator in Python has more than one meaning attached to it. We can use it as a Multiplication operator, Repetition operator, used for Unpacking the iterables, and Used as function *args.

Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.

As the multiplication operator

Generally, the start (*) operator is used for multiplication purposes. For numeric data the asterisk (*) is used as a multiplication operator. Let’s take an example and see how the star operator works on numeric operands.

Example

a = 100
b = 29
result = a * b
print("Output: ", result)

Output

Output:  2900

As the repetition operator

For sequences like list, string and tuples, the star operator is used as a repetition operator.

Example

s = "Python"
result = s * 3
print("Output for string sequence: ", result)

l = [1, 'a', 3]
l_result = l * 2
print("Output for list sequence: ", l_result)

t = (1, 2, 3)
t_result = t * 4
print("Output for tuple sequence: ", t_result)

Output

Output for string sequence:  PythonPythonPython
Output for list sequence:  [1, 'a', 3, 1, 'a', 3]
Output for tuple sequence:  (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

To unpack the iterables

When calling a function, the asterisk operator can be used as a parameter to unpack the argument iterables.

Example

def foo(a, b, c):
    return(a, b, c)

l = [1, 2, 3]
print(' ',foo(*l))

Output

(1, 2, 3)

Example

The list iterable is unpacked by using the start (*) operator. It is also the same while sending iterables like tuple and dictionary as a parameter.

def foo(a, b, c):
    return(a, b, c)

t = (1, 4, 6)
print('Output tuple unpacking: ',foo(*t))

d = {'a': 10, 'b': 20, 'c': 30}
print('Output dictionary unpacking: ',foo(*d))

Output

Output tuple unpacking:  (1, 4, 6)
Output dictionary unpacking:  ('a', 'b', 'c')

The iterables tuple and dictionaries are also unpacked by using the asterisk (*) operator while calling a function.

To create function *args (positional arguments):

While defining a function the single asterisk (*) is used to pass a variable number of arguments to a function. It is nothing but creating a function with non key-word arguments.

Example

The above example is defined to take any number of values and able to add them all together using *args.

def add_values(*args):
  return sum(args)
 
print(add_values(1, 3, 4, 2))
print(add_values(10, 2, 4, 5, 6, 7, 8, 10))

Output

10
52

Updated on: 09-Sep-2023

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements