⚙️ Built-in Array Functions

NumPy comes packed with convenient functions that generate arrays with specific patterns, sequences, and structures. These built-in functions are incredibly useful for initializing data, creating test arrays, and setting up mathematical operations.

Let's explore the most practical and powerful array generation functions!

import numpy as np

# Quick preview of built-in functions
zeros = np.zeros(4)
ones = np.ones(3) 
sequence = np.arange(1, 8, 2)
spaced = np.linspace(0, 10, 5)

print(f"Zeros: {zeros}")
print(f"Ones: {ones}")
print(f"Sequence: {sequence}")
print(f"Evenly spaced: {spaced}")

🟦 zeros() - Arrays of Zeros

Perfect for initializing arrays that you'll fill with calculated values, counters, or results.

import numpy as np

# Different zero array patterns
simple_zeros = np.zeros(5)
matrix_zeros = np.zeros((3, 4))
cube_zeros = np.zeros((2, 2, 2))  # 3D array

print(f"1D zeros: {simple_zeros}")
print(f"2D zeros: \n{matrix_zeros}")
print(f"3D zeros shape: {cube_zeros.shape}")

# Practical example: score accumulator
num_teams = 4
team_scores = np.zeros(num_teams)
print(f"Initial scores: {team_scores}")

# Add some scores
team_scores[0] = 15
team_scores[2] = 23
print(f"Updated scores: {team_scores}")

🟨 ones() - Arrays of Ones

Great for default values, scaling factors, masks, and mathematical operations.

import numpy as np

# Creating arrays of ones
basic_ones = np.ones(4)
matrix_ones = np.ones((3, 3))
custom_type = np.ones(5, dtype=int)

print(f"Basic ones: {basic_ones}")
print(f"Matrix ones: \n{matrix_ones}")
print(f"Integer ones: {custom_type}")

# Practical example: default multipliers
base_values = np.array([10, 20, 30])
multipliers = np.ones(3) * 1.5  # 50% increase
result = base_values * multipliers
print(f"Original: {base_values}")
print(f"Multiplied: {result}")

🔢 arange() - Number Sequences

Like Python's range() but returns a NumPy array. Perfect for creating indices, loops, and sequential data.

import numpy as np

# Different arange patterns
simple = np.arange(6)           # 0 to 5
range_vals = np.arange(2, 10)   # 2 to 9
with_step = np.arange(0, 20, 3) # 0, 3, 6, 9, 12, 15, 18
backwards = np.arange(10, 0, -2) # 10, 8, 6, 4, 2
decimals = np.arange(0, 2, 0.5)  # 0, 0.5, 1.0, 1.5

print(f"Simple: {simple}")
print(f"Range: {range_vals}")
print(f"Step 3: {with_step}")
print(f"Backwards: {backwards}")
print(f"Decimals: {decimals}")

# Practical example: time steps
time_hours = np.arange(0, 24, 2)  # Every 2 hours
print(f"Time points: {time_hours}")

📏 linspace() - Evenly Spaced Numbers

Creates a specific number of evenly spaced values between two endpoints. Perfect for plotting, sampling, and scientific applications.

import numpy as np

# Evenly spaced arrays
five_points = np.linspace(0, 10, 5)    # 5 points from 0 to 10
ten_points = np.linspace(0, 1, 10)     # 10 points from 0 to 1
angles = np.linspace(0, 180, 7)        # 7 angles from 0 to 180°

print(f"5 points (0-10): {five_points}")
print(f"10 points (0-1): {ten_points}")
print(f"Angles: {angles}")

# Exclude endpoint
no_endpoint = np.linspace(0, 10, 5, endpoint=False)
print(f"No endpoint: {no_endpoint}")

# Practical example: smooth curve points
curve_x = np.linspace(-2, 2, 9)  # 9 points for smooth curve
print(f"Curve X values: {curve_x}")

🎯 full() - Custom Fill Values

Create arrays filled with any value you specify. Perfect for default values, constants, and initialization.

import numpy as np

# Arrays with custom values
sevens = np.full(4, 7)
pi_values = np.full((2, 3), 3.14159)
negatives = np.full(5, -1.5)

print(f"Sevens: {sevens}")
print(f"Pi matrix: \n{pi_values}")
print(f"Negatives: {negatives}")

# Practical example: default temperature
cities = 5
default_temp = 20.0  # 20°C
temperatures = np.full(cities, default_temp)
print(f"Default temperatures: {temperatures}")

# Update specific cities
temperatures[0] = 25.5  # City 1 is warmer
temperatures[3] = 18.2  # City 4 is cooler
print(f"Updated temperatures: {temperatures}")

🔍 eye() - Identity Matrices

Creates identity matrices (1s on the diagonal, 0s elsewhere). Essential for linear algebra and matrix operations.

import numpy as np

# Identity matrices
id_3x3 = np.eye(3)
id_4x4 = np.eye(4)
id_2x2 = np.eye(2)

print(f"3x3 Identity: \n{id_3x3}")
print(f"4x4 Identity: \n{id_4x4}")

# Practical example: transformation matrix base
print("🔄 Identity as transformation base:")
transform = np.eye(3)
print(f"Base transform: \n{transform}")
# You can modify this for scaling, rotation, etc.

🔀 logspace() - Logarithmically Spaced Numbers

Creates numbers spaced evenly on a logarithmic scale. Useful for scientific applications, especially when dealing with exponential relationships.

import numpy as np

# Logarithmically spaced values
log_values = np.logspace(0, 3, 4)  # 10^0 to 10^3, 4 points
log_base2 = np.logspace(1, 4, 4, base=2)  # 2^1 to 2^4, 4 points

print(f"Log base 10: {log_values}")
print(f"Log base 2: {log_base2}")

# Practical example: frequency analysis
frequencies = np.logspace(1, 4, 6)  # 10 Hz to 10 kHz
print(f"Frequencies (Hz): {frequencies}")

🎲 random Module Preview

NumPy also has powerful random number generation (covered in detail later):

import numpy as np

# Quick random examples
random_values = np.random.random(5)      # Random 0-1
random_ints = np.random.randint(1, 10, 5) # Random integers 1-9
normal_dist = np.random.normal(0, 1, 5)   # Normal distribution

print(f"Random 0-1: {random_values}")
print(f"Random ints: {random_ints}")
print(f"Normal dist: {normal_dist}")

🛠️ _like Functions - Match Existing Arrays

Create new arrays with the same shape as existing ones:

import numpy as np

# Base array to match
original = np.array([[1, 2, 3], [4, 5, 6]])

# Create arrays with same shape
zeros_like = np.zeros_like(original)
ones_like = np.ones_like(original)
full_like = np.full_like(original, 99)

print(f"Original: \n{original}")
print(f"Zeros like: \n{zeros_like}")
print(f"Ones like: \n{ones_like}")
print(f"Full like: \n{full_like}")

# Practical example: results array
data_matrix = np.array([[10, 20], [30, 40], [50, 60]])
results = np.zeros_like(data_matrix, dtype=float)
print(f"Results template: \n{results}")

🎯 Choosing the Right Function

Here's a quick guide for selecting the best function:

FunctionBest ForExample Use
np.zeros()Initializing counters, resultsScore tracking, algorithm results
np.ones()Default values, scalingMultipliers, boolean masks
np.arange()Sequential indices, loopsArray indexing, time steps
np.linspace()Smooth sampling, plottingGraph coordinates, smooth curves
np.full()Custom default valuesDefault settings, constant arrays
np.eye()Linear algebraMatrix operations, transformations
_like functionsMatch existing shapesTemplate arrays, consistent sizing

💡 Practical Combination Examples

Let's see these functions work together in real scenarios:

import numpy as np

print("🎯 Practical Function Combinations")
print("=" * 35)

# Example 1: Setting up a simulation
num_particles = 6
positions = np.zeros((num_particles, 2))  # x, y coordinates
velocities = np.ones((num_particles, 2))  # default velocity
time_steps = np.arange(0, 10, 0.5)       # time points

print(f"Particles: {num_particles}")
print(f"Time steps: {len(time_steps)}")

# Example 2: Creating test data
test_size = 8
test_inputs = np.linspace(-1, 1, test_size)
expected_outputs = np.full(test_size, 0.5)  # Expected result
actual_results = np.zeros_like(expected_outputs)

print(f"Test inputs: {test_inputs}")
print(f"Expected: {expected_outputs}")

# Example 3: Matrix setup
matrix_size = 3
identity = np.eye(matrix_size)
data_matrix = np.full((matrix_size, matrix_size), 2)
combined = identity + data_matrix

print(f"Combined matrix: \n{combined}")

🎯 Key Takeaways

🚀 What's Next?

Perfect! You now have a complete toolkit for creating arrays in any way you need. Next, let's explore array properties - understanding shape, dimensions, and how NumPy organizes your data.

Continue to: Array Shape and Dimensions

Ready to understand array structure! 📐✨

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent