In Python, the `*` operator can be used in several contexts, including elementwise multiplication when working with NumPy arrays. Here are typical uses of the `*` operator with arrays:
1. **Elementwise Multiplication**:
When using NumPy arrays, the `*` operator performs elementwise multiplication.
```python
import numpy as np
# Define two NumPy arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Elementwise multiplication
result = a * b
print("Elementwise multiplication:", result)
# Output: [ 4 10 18 ]
```
2. **Scalar Multiplication**:
When a NumPy array is multiplied by a scalar, each element of the array is multiplied by that scalar.
```python
import numpy as np
# Define a NumPy array
a = np.array([1, 2, 3])
# Scalar multiplication
scalar = 2.5
result = a * scalar
print("Scalar multiplication:", result)
# Output: [2.5 5. 7.5]
```
3. **Broadcasting**:
NumPy's broadcasting rules allow you to perform elementwise operations on arrays of different shapes. For example, you can multiply a 2D array by a 1D array (vector) where the operation is applied to each row.
```python
import numpy as np
# Define a 2D NumPy array and a 1D NumPy array
A = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([1, 2, 3])
# Broadcasting multiplication
result = A * b
print("Broadcasting multiplication:\n", result)
# Output:
# [[ 1 4 9]
# [ 4 10 18]]
```
4. **Elementwise Operations with Boolean Arrays**:
You can also perform elementwise operations with boolean arrays, which can be useful for masking or conditional operations.
```python
import numpy as np
# Define a NumPy array
a = np.array([1, 2, 3, 4, 5])
# Create a boolean mask
mask = a > 3
# Elementwise multiplication with the mask
result = a * mask
print("Elementwise multiplication with boolean mask:", result)
# Output: [0 0 0 4 5]
```
5. **Matrix Multiplication (Dot Product)**:
Although not directly related to the `*` operator, for completeness, it's important to note that the `@` operator or `numpy.dot` function is used for matrix multiplication (dot product) rather than elementwise multiplication.
```python
import numpy as np
# Define two 2D NumPy arrays (matrices)
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Matrix multiplication
result = A @ B
print("Matrix multiplication:\n", result)
# Output:
# [[19 22]
# [43 50]]
```
In summary, the `*` operator is used for elementwise multiplication and scalar multiplication when working with NumPy arrays, and it can take advantage of broadcasting for operations on arrays of different shapes. For matrix multiplication, the `@` operator or `numpy.dot` function should be used instead.