0
0
NumpyHow-ToBeginner ยท 3 min read

How to Create Array in NumPy: Syntax and Examples

To create an array in numpy, use the numpy.array() function with a list or tuple as input. This function converts the input into a NumPy array, which is efficient for numerical operations.
๐Ÿ“

Syntax

The basic syntax to create a NumPy array is:

  • numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Here:

  • object: A sequence like list or tuple to convert into an array.
  • dtype: (Optional) Data type of the array elements.
  • copy: (Optional) Whether to copy the data or not.
  • order: (Optional) Memory layout order.
  • ndmin: (Optional) Minimum number of dimensions for the array.
python
import numpy as np

# Basic syntax to create an array
arr = np.array([1, 2, 3])
๐Ÿ’ป

Example

This example shows how to create a 1D and 2D NumPy array from lists and print them.

python
import numpy as np

# Create a 1D array
array_1d = np.array([10, 20, 30, 40])

# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("1D array:")
print(array_1d)
print("\n2D array:")
print(array_2d)
Output
1D array: [10 20 30 40] 2D array: [[1 2 3] [4 5 6]]
โš ๏ธ

Common Pitfalls

Common mistakes when creating arrays include:

  • Passing a single number instead of a list or tuple, which creates a zero-dimensional array.
  • Mixing data types in the input list, which causes NumPy to upcast to a common type.
  • Forgetting to import NumPy before using array().

Example of wrong and right usage:

python
import numpy as np

# Wrong: passing a single number creates a 0D array
single_num = np.array(5)
print("0D array:", single_num)

# Right: pass a list to create 1D array
list_num = np.array([5])
print("1D array:", list_num)
Output
0D array: 5 1D array: [5]
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample
numpy.array()Create array from list or tuplenp.array([1, 2, 3])
numpy.zeros()Create array filled with zerosnp.zeros((2,3))
numpy.ones()Create array filled with onesnp.ones((3,2))
numpy.arange()Create array with range of valuesnp.arange(5)
numpy.linspace()Create array with evenly spaced valuesnp.linspace(0, 1, 5)
โœ…

Key Takeaways

Use numpy.array() with a list or tuple to create arrays.
Arrays can be one-dimensional or multi-dimensional depending on input.
Passing a single number creates a zero-dimensional array, not a list.
NumPy automatically infers data type but you can specify it with dtype.
Always import numpy as np before creating arrays.