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

Usage of Asterisks in Python


Python programming language uses both * and ** on different contexts. In this article we will see how these two are used and what the respective useful scenarios.

As an Infix Operator

When * is used as infix operator, it basically gives the mathematical product of numbers. IN the below example we take integers. Floats and complex numbers to multiply and get the results.

Example

# Integers
x = 20
y = 10
z = x * y
print(z,"\n")

# Floats
x1 = 2.5
y1 = 5.1
z1 = x1 * y1
print(z1,"\n")

# Complex Numbers
x2 = 4 + 5j
y2 = 5 + 4j
z2 = x2 * y2
print(z2,"\n")

Output

Running the above code gives us the following result −

200
12.75
41j

We can also use it as infix operator to extend the strings.

Example

str = "Point-"
print(str * 4,"\n")
List = [4, 5, 6]
print(List * 3,"\n")
Tuple = (9, 8, 7)
print(Tuple * 2)

Output

Running the above code gives us the following result −

Point-Point-Point-Point-
[4, 5, 6, 4, 5, 6, 4, 5, 6]
(9, 8, 7, 9, 8, 7)

As a Prefix Operator

We can use a single asterisk as a prefix. The below examples describe various examples of how we can use it as a prefix.

Expand an Iterable

An iterable like list or tuple can be expanded by just prefixing its name with an asterisk.

Example

week_days =['Mon','Tue','Wed','Thu','Fri']
print(week_days)

Output

Running the above code gives us the following result −

Mon Tue Wed Thu Fri

Take Variable Number of Arguments

We can give variable number of arguments to a function using a single asterisk symbol. It is as shown in the below program.

Example

def many_sums(*args):
   res = 0
   # Iterating over the Python args tuple
   for x in args:
   res = res + x
   return res
print(many_sums(1, 2))
print(many_sums(11, 21, 30))
print(many_sums(5.5,0))

Output

Running the above code gives us the following result −

3
62
5.5

Using **

The double asterisk is used for keyword based arguments. Here the argument is passed in as dictionary and not as individual values.

Example

def join_keys(**kwargs):
   result = ""
   # Iterating over kwargs dictionary keys
   for arg in kwargs.keys():
   result += arg
   return result
def join_values(**kwargs):
   result = ""
   # Iterating over kwargs dictionary values
   for arg in kwargs.values():
   result += arg
   return result
print(join_keys(day1="Mon-", day2="Tue-", day3="Wed-", day4="Thu-"))
print(join_values(day1="Mon-", day2="Tue-", day3="Wed-", day4="Thu-"))

Output

Running the above code gives us the following result −

day1day2day3day4
Mon-Tue-Wed-Thu-