Labs ICT
Pro Login

Your First Array

Creating and inspecting your very first NumPy array.

Your First Array

Alright, let's create your first NumPy array. Think of it like cooking your first meal - you start with simple ingredients and build from there.

Creating a Basic Array

The np.array() function is your starting point. You pass it a list and it converts it to a NumPy array.


import numpy as np

my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)

print(my_array)
print(type(my_array))
    

You'll see the array printed and the type will show numpy.ndarray. That "nd" stands for n-dimensional, which makes sense because NumPy arrays can have any number of dimensions.

Checking Array Properties

Let me give you some useful functions to inspect your arrays.


import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(f"Array: {arr}")
print(f"Shape: {arr.shape}")
print(f"Size: {arr.size}")
print(f"Dimensions: {arr.ndim}")
print(f"Data type: {arr.dtype}")
    

One thing that confused me at first was the difference between shape and size. Shape tells you the dimensions (like 5 for 1D, or 3x4 for 2D). Size tells you the total number of elements.

Multi-dimensional Arrays

You can create 2D arrays by passing nested lists. This is like creating a table or matrix.


import numpy as np

nested_list = [[1, 2, 3], [4, 5, 6]]
matrix = np.array(nested_list)

print(matrix)
print(f"Shape: {matrix.shape}")
print(f"Dimensions: {matrix.ndim}")
    

Notice how shape shows (2, 3) - that's 2 rows and 3 columns. The ndim shows 2 because it's a 2D array.

Try it Yourself →

Key Takeaways

  • Use np.array() to create arrays from Python lists
  • Arrays have attributes: shape, size, ndim, dtype
  • Shape shows dimensions, size shows total elements
  • Multi-dimensional arrays are created with nested lists