Python Superstar: 5 Ways to Use the * Operator

0
(0)

The asterisk ( *) symbol in Python is a versatile operator that serves both as a multiplication or exponentiation operator and for manipulating arguments in functions.

Beginners only need to know its basic use as a multiplication operator. However, if you’re looking to become a Python expert, you’ll need to deepen your knowledge! It’s time to discover just how useful and powerful the asterisk is in Python.

In this article, we will look at 5 ways to use the operator *with descriptions and examples, from elementary to more complex.

Method 1: Multiply or raise to a power

The most obvious is to use asterisks as mathematical operators:

  • *– multiplication operation.
  • **– operation of raising to a power.
2*3
# 6

2**3
# 9

Method 2: Any number of function arguments

A function does not necessarily have to receive a fixed number of arguments.

Let’s say you don’t know in advance how many arguments will be passed. This is where “asterisks” can come to your rescue!

def print_genius(*names):
print(type(names))
for n in names:

print(n)

print_genius(‘Elon Mask’, ‘Mark Zuckerberg ‘, ‘Yang Zhou’)

# class 'tuple'
# Elon Mask
# Mark Zuckerberg

# Yang Zhou
def top_genius(**names):
print(type(names))

for k, v in names.items():

print(k, v)

top_genius(Top1=“Elon Mask”, Top2=“Mark Zuckerberg”, Top3=“Yang Zhou”)

# class 'dict'
# Top1 Elon Mask
# Top2 Mark Zuckerberg
# Top3 Yang Zhou

As shown in the above example, when defining a function, we can define a parameter with a prefix of one or two asterisks to pass an unlimited number of arguments.

  • A prefixed parameter *can write any number of positional arguments to tupleThe arguments list.
  • A prefixed parameter **Can take any number of named arguments and form a dictionary from them.dict

If the number of arguments to a function cannot be determined in advance, then we define it as follows:

def func(*args, **kwargs):
pass

Generally speaking, anything can be used instead of args“and” —it’s just a common convention. You can write ” and” instead. But that won’t make things any clearer kwargsteacoffee

Method 3: Controlling named arguments

Another useful use of asterisks is to force a function to accept only named arguments.

For example,

def genius(*, first_name, last_name):
print(first_name, last_name)
genius(‘Yang’,‘Zhou’)

# TypeError: genius() takes 0 positional arguments but 2 were given
genius(first_name='Yang', last_name='Zhou')
# Yang Zhou

As shown in the example above, a single asterisk *introduces a restriction: all subsequent arguments must be named arguments.

If we need to impose a restriction on multiple named arguments and leave some arguments positional, we simply need to put the positional arguments before the asterisk:

def genius(age, *, first_name, last_name):
print(first_name, last_name, 'is', age)
genius(28, first_name=‘Yang’, last_name=‘Zhou’)

# Yang Zhou is 28

In this example, if you had entered ‘Yang’ without the keyword first_name, you would have received an error.

Method 4: Unpacking objects

We can use asterisks to unpack tuples, lists, dictionaries, and other iterables, making our programs clear and elegant.

For example, if we want to combine elements of different iterables, say one list, one tuple, and one set, into a new list, what should we do?

Obviously, we can use loops forto iterate over all the elements and add them to the new list one by one:

A = [1, 2, 3]
B = (4, 5, 6)
C = {7, 8, 9}

L = []

for a in A:

L.append(a)
for b in B:
L.append(b)
for c in C:
L.append(c)

print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]

This way, we can accomplish our mission, but the code looks very long and is not very optimized. A better method is to use a list comprehension:

A = [1, 2, 3]
B = (4, 5, 6)
C = {7, 8, 9}

L = [a for a in A] + [b for b in B] + [c for c in C]
print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]

We’ve reduced three for loops to one line. This is already good code, but it’s not the simplest method! We can make it even more beautiful.

It’s time to see how beautiful the stars are in this situation 

A = [1, 2, 3]
B = (4, 5, 6)
C = {7, 8, 9}

L = [*A, *B, *C]
print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]

As shown in the example above, we can use an asterisk as a prefix for objects to unpack their elements. Incidentally, if we use an *asterisk as a prefix for a dictionary, its keys will be unpacked. If we use double asterisks **as a prefix, its values ​​will be unpacked. However, we must use the keys to retrieve the unpacked values. Because of this inconvenience, it’s not common practice to extract elements from a dictionary using asterisks.

D = {'first': 1, 'second': 2, 'third': 3}

print(*D)
# first second third

# print(**D)
# TypeError: 'first' is an invalid keyword argument for print()

print('{first},{second},{third}'.format(**D))
# 1,2,3

Method 5: Multiple assignments

This unpacking syntax was introduced in PEP 3132 to make our code more elegant.

This PEP allows you to specify a “catch-all” name that will contain all the elements in a list that don’t have a “regular” name.

Simple example:

L = [1, 2, 3, 4, 5, 6, 7, 8]
a,*b = L
print(a)
# 1
print(b)
# [2, 3, 4, 5, 6, 7, 8]

Conclusion

The asterisk is one of the most frequently used operators in programming in any language. However, Python has many interesting constructs that can and should be used. This will demonstrate your professionalism and also make your code more readable and of higher quality.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email

Leave a Reply

Your email address will not be published. Required fields are marked *