What is ** Operator in Python: Explanation and Examples
** operator is used for exponentiation, meaning it raises a number to the power of another (e.g., 2 ** 3 equals 8). It is also used to unpack dictionaries into function arguments when calling functions.How It Works
The ** operator in Python has two main uses. First, it acts as the exponentiation operator, which means it raises a number to the power of another number. For example, 3 ** 2 means 3 multiplied by itself 2 times, resulting in 9. Think of it like repeated multiplication, similar to how you might calculate the area of a square by multiplying its side length by itself.
Second, ** is used to unpack dictionaries when calling functions. Imagine you have a box of labeled ingredients (a dictionary), and you want to pass each ingredient separately to a recipe (function). Using ** spreads out the dictionary’s key-value pairs into named arguments the function can use. This makes your code cleaner and easier to read.
Example
This example shows both uses of the ** operator: exponentiation and dictionary unpacking in a function call.
def greet(name, age): return f"Hello, {name}! You are {age} years old." # Exponentiation example power = 2 ** 4 # 2 to the power of 4 # Dictionary unpacking example person = {'name': 'Alice', 'age': 30} message = greet(**person) print(f"2 ** 4 = {power}") print(message)
When to Use
Use the ** operator for exponentiation whenever you need to calculate powers, such as in math problems, physics calculations, or financial growth models.
Use dictionary unpacking with ** when you want to pass many named arguments to a function without listing each one manually. This is especially helpful when the arguments come from a dictionary or when you want to forward arguments from one function to another cleanly.
Key Points
**raises a number to a power (exponentiation).- It unpacks dictionaries into named function arguments.
- Using
**for unpacking makes code cleaner and more flexible. - Exponentiation with
**is right-associative (e.g.,2 ** 3 ** 2equals2 ** (3 ** 2)).