Computer >> Computer tutorials >  >> Programming >> Python

What does the Star operator mean in Python?


The asterisk (star) operator is used in Python with more than one meaning attached to it.

For numeric data types, * is used as multiplication operator

>>> a=10;b=20
>>> a*b
200
>>> a=1.5; b=2.5;
>>> a*b
3.75
>>> a=2+3j; b=3+2j
>>> a*b
13j

For sequences such as string, list and tuple,  * is a repetition operator

>>> s="Hello"
>>> s*3
'HelloHelloHello'
>>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> T1=(1,2,3)
>>> T1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

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

>>> def function(*arg):
    print (type(arg))
    for i in arg:
      print (i)


>>> function(1,2,3)
<class 'tuple'>
1
2
3