Python Superstar: 5 Ways to Use the * Operator
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 Zhoudef 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 totupleThe 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 clearerkwargsteacoffee
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.
Explore More IT Terms
#
A
- A Guide to SQL Query Formatting
- A/B testing
- Agile
- Algorithm complexity in 5 minutes
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data structures
- Defining Aliases
- Defining Arrays
- Deque
- Developing a Website from Scratch
- Digital data: understand the importance of this asset for businesses.
- Doubly linked lists
E
F
H
- Handling errors and exceptions
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Inserting an Image
- Interactive Python Tutorial – Learn Programming from Scratch
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to programming languages
- IT Specialist Resume (CV)
K
M
P
S
- SFML Graphics Library Tutorials
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Statistical analysis: importance for decision making.
- String formatting in Python
- Swift Lessons
- switch/match construct
T
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a GPU in a computer, in simple terms?
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview
