Python Star or Asterisk Operator

Python Star/Asterisk Operator(*):

 

  • It means, multiple values can be stored inside that variables.
  • In function “*” allows you to consume all remaining arguments.
  • It allows an unspecified number of arguments and it consumes all of them.

 

 


 

How Asterisk works with functions:

01. Example

def argFunction(x, y):
  print("Type Of x: ",type(x),", Value Of x: ", x)
  print("Type Of y: ",type(y),", Value Of y: ", y)

argFunction("zerones", 20, 34, 35, 'programming')

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-a4bc297d481b> in <module>
      3   print("Type Of y: ",type(y)," Value Of y: ", y)
      4 
----> 5 argFunction("zerones", 20, 34, 35, 'programming')

TypeError: argFunction() takes 2 positional arguments but 5 were given

 

02. Example

def argFunction(x, *y):
  print("Type Of x: ",type(x),", Value Of x: ", x)
  print("Type Of y: ",type(y),", Value Of y: ", y)

argFunction(67, "zerones", 20, 34, 35)

Output:

Type Of x:  <class 'int'>  Value Of x:  67
Type Of y:  <class 'tuple'>  Value Of y:  ('zerones', 20, 34, 35)

 

03. Example

def argFunction(x, *y):
  print("Type Of x: ",type(x),", Value Of x: ", x)
  print("Type Of y: ",type(y),", Value Of y: ", y)

argFunction("zerones", 20, 34, 35, 'programming')

Output:

Type Of x:  <class 'str'>  Value Of x:  zerones
Type Of y:  <class 'tuple'>  Value Of y:  (20, 34, 35, 'programming')

 


 

How Asterisk works with variables:

01. Example

x, y = "zeroones",5
print("Type Of x: ",type(x),", Value Of x: ", x)
print("Type Of y: ",type(y),", Value Of y: ", y)

Output:

Type Of x:  <class 'str'>  Value Of x:  zeroones
Type Of y:  <class 'int'>  Value Of y:  5

 

02. Example

x, y = 10,"zeroones",5
print("Type Of x: ",type(x),", Value Of x: ", x)
print("Type Of y: ",type(y),", Value Of y: ", y)

Output:

ValueError                                Traceback (most recent call last)
<ipython-input-9-d1e8d98076cc> in <module>
----> 1 x, y = 10,"zeroones",5
      2 print("Type Of x: ",type(x)," Value Of x: ", x)
      3 print("Type Of y: ",type(y)," Value Of y: ", y)

ValueError: too many values to unpack (expected 2)

 

03. Example

x, *y = 10,"zeroones",5
print("Type Of x: ",type(x),", Value Of x: ", x)
print("Type Of y: ",type(y),", Value Of y: ", y)

Output:

Type Of x:  <class 'int'>  Value Of x:  10
Type Of y:  <class 'list'>  Value Of y:  ['zeroones', 5]

 

04. Example

x, *y = "Python","Java","Cpp"
print("Type Of x: ",type(x),", Value Of x: ", x)
print("Type Of y: ",type(y),", Value Of y: ", y)

Output:

Type Of x:  <class 'str'> , Value Of x:  Python
Type Of y:  <class 'list'> , Value Of y:  ['Java', 'Cpp']

 

05. Example

y = *x
print(type(y))

Output:

  File "<ipython-input-12-0a5464c5b4d0>", line 4
SyntaxError: can't use starred expression here

 

Leave a comment