Usage of Asterisks in Python

Python programming language uses both * and ** in different contexts. In this article, we will explore how these operators are used and their practical applications.

As an Infix Operator

When * is used as an infix operator, it performs mathematical multiplication on numbers. Let's see examples with integers, floats, and complex numbers ?

# Integers
x = 20
y = 10
z = x * y
print(z)

# Floats
x1 = 2.5
y1 = 5.1
z1 = x1 * y1
print(z1)

# Complex Numbers
x2 = 4 + 5j
y2 = 5 + 4j
z2 = x2 * y2
print(z2)
200
12.75
(-5+41j)

String and Sequence Repetition

We can also use * as an infix operator to repeat strings, lists, and tuples ?

text = "Point-"
print(text * 4)

numbers = [4, 5, 6]
print(numbers * 3)

tuple_data = (9, 8, 7)
print(tuple_data * 2)
Point-Point-Point-Point-
[4, 5, 6, 4, 5, 6, 4, 5, 6]
(9, 8, 7, 9, 8, 7)

As a Prefix Operator (*args)

A single asterisk as a prefix has several important uses in Python function definitions and calls.

Unpacking Iterables

An iterable like a list or tuple can be unpacked by prefixing its name with an asterisk ?

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

Variable Number of Arguments

We can accept a variable number of positional arguments in a function using *args ?

def many_sums(*args):
    result = 0
    # Iterating over the Python args tuple
    for x in args:
        result = result + x
    return result

print(many_sums(1, 2))
print(many_sums(11, 21, 30))
print(many_sums(5.5, 0))
3
62
5.5

Using Double Asterisk (**kwargs)

The double asterisk is used for keyword-based arguments. The arguments are passed as a dictionary, allowing functions to accept any number of named parameters ?

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-"))
day1day2day3day4
Mon-Tue-Wed-Thu-

Unpacking Dictionaries

You can also use ** to unpack dictionaries when calling functions ?

def greet(name, age, city):
    return f"Hello {name}, age {age}, from {city}"

person_info = {"name": "Alice", "age": 25, "city": "New York"}
print(greet(**person_info))
Hello Alice, age 25, from New York

Conclusion

The asterisk operators in Python serve multiple purposes: * for multiplication, sequence repetition, unpacking iterables, and collecting variable arguments, while ** handles keyword arguments and dictionary unpacking. Understanding these operators is essential for writing flexible and efficient Python code.

Updated on: 2026-03-15T17:31:29+05:30

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements