Hello and welcome! Today we get to know arrays using a powerful Python library, NumPy. An array is like a line of boxes, each storing some data, and the stored data must all be of the same type. Arrays make data manipulation much easier in many programming languages, including Python. Ready to discover the magic of arrays? Let's dive in!
An array in programming is a special variable that can hold several values of the same type at a time. Think of a bookshelf with books or a kitchen cabinet with dishes. Arrays make your program more organized and play a significant role in data analysis and data manipulation.
Python doesn't have built-in support for arrays, but it does have a data structure called lists. Lists are versatile, but they are not optimized for mathematical operations. This is where the NumPy library comes in. NumPy provides support for arrays and a wide range of mathematical functions. When you think of arrays in Python, think of NumPy!
To use NumPy, import it into your Python program as follows: import numpy as np
.
Let's create our first array using the np.array()
function:
Python1import numpy as np 2 3# Creating an array 4arr1D = np.array([1, 2, 3, 4, 5]) 5print(f"Our first 1D array: {arr1D}") # [1, 2, 3, 4, 5]
Here we've created an array arr1D
that stores the numbers 1
to 5
. Now let's see how to access and modify these elements.
NumPy also provides functions to create arrays with default initial values. Let's check them:
Python1import numpy as np 2 3# Array of all zeros 4zeros = np.zeros(5) 5print(f"All zeros: {zeros}") # [0. 0. 0. 0. 0.] 6 7# Array of all ones 8ones = np.ones(5) 9print(f"All ones: {ones}") # [1. 1. 1. 1. 1.] 10 11# Empty array 12empty = np.empty(5) 13print(f"Empty array: {empty}") # May vary; random, uninitialized numbers. 14 15# Sequence of numbers in NumPy array 16sequence = np.arange(0, 10, 2) 17print(f"Sequence: {sequence}") # [0 2 4 6 8]
These functions like np.zeros()
, np.ones()
, np.empty()
, and np.arange()
can quickly create arrays filled with specific values or a range of numbers. The arguments of the np. arrange
function work similarly to the ones of the python's range
function: the first value is the start of the sequence, the second one is the end of it, and the last one is the step.
Excellent! Today, we mastered the importance of arrays, explored the NumPy library, and created our first NumPy array. Plus, we learned various built-in techniques to create arrays quickly using NumPy.
Now, it's time to apply your knowledge to the practice exercises in the next section. Happy coding, and remember, practice makes perfect!