Create one-dimensional and two-dimensional NumPy arrays from lists
Expt. No.20
Page No.40
NumPy arrays from lists
Aim
To write a Python program that creates a one-dimensional and a two-dimensional NumPy array from lists and displays them with their type.
Concepts used
Algorithm
- Import numpy as np.
- Create a 1-D array from a list of numbers with np.array().
- Create a 2-D array from a list of lists.
- Display each array and its type.
Program
# NumPy arrays from lists import numpy as np marks = [78, 85, 69, 92]arr1 = np.array(marks)print("1-D array:", arr1)print("Type :", type(arr1)) table = [[1, 2, 3], [4, 5, 6]]arr2 = np.array(table)print("2-D array:")print(arr2)print("Type :", type(arr2))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python numpy_arrays.py
1-D array: [78 85 69 92]
Type : <class 'numpy.ndarray'>
2-D array:
[[1 2 3]
[4 5 6]]
Type : <class 'numpy.ndarray'>
✓ Printed by running this program, not typed by hand.
Result
The list [78, 85, 69, 92] became a 1-D array printed without commas, and the list of two lists became a 2-D array of 2 rows and 3 columns. Both have the type numpy.ndarray.
Viva voce: what the examiner may ask
01What is NumPy?
A Python library for working with arrays of numbers quickly.
02How does a NumPy array differ from a list?
All elements of an array have the same type, and arithmetic works on the whole array at once.
03What does import numpy as np do?
It imports NumPy and lets you call it by the shorter name np.
Variations for the lab test
- Create an array from a list of decimal numbers and display it.
- Create a 2-D array of 3 rows from three lists of marks.
- Create an array from a list that mixes integers and decimals and see what happens.
! Common mistake Writing
np.array(1, 2, 3) instead of np.array([1, 2, 3]) raises an error: the values must be passed as one list.