2. Array creation
1• To create a one-dimensional NumPy array, we can simply pass a Python list to the array() method
Example 3
( )
( )
3. • We can easily make out the difference between a list and an array
representation in Python. In list, elements are separated by a comma,
whereas an array is like a collection of elements without a comma
separator in between.
import numpy as np
lst = [1,2, 3,4]
a=np.array (lst)
print(lst)
print (a)
a
[1, 2, 3, 4]
[1 2 3 4]
array([1, 2, 3, 4])
5. Creation of 2D NumPy Array
• multiple lists can be used to create 2D arrays. To create a two-dimensional array, you can pass a list of lists to
the array method as shown below:
6. Dimension
NumPy Arrays provides the ndim attribute that returns an integer that
tells us how many dimensions the array have
import numpy as np
a = np.array(42)
b = np.array([1,2,3,4,5])
c = np.array([[1,2,3], [4,5,6]])
print("Dimension of array a is:", a.ndim)
print("Dimension of array b is:",b.ndim)
print("Dimension of array c is:",c.ndim)
7. Access Array Elements
• Array element can be accessed by referring to its index
number.
• The indexes in NumPy arrays start with 0, meaning that the
first element has index 0, and the second has index 1 etc.
Get third and fourth
elements from the array and
add them.
import numpy as np
arr = np.array([1,2,3,4])
print("The first element is :", arr[0])
print("The 2nd element is :",arr[1])
print("Sum of 3rd and 4th elements are :",arr[2] + arr[3])
8. • To access elements from 2-D arrays we can use comma
separated integers representing the dimension and the
index of the element.
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st dim: ', arr[0, 1])#Access the 2nd element on 1st dim:
print('5th element on 2nd dim: ', arr[1, 4])#Access the 5th element on 2nd dim:
print('Last element from 2nd dim: ', arr[1, -1])#Use negative indexing to access an array from the end.
Ouput: 10
Example
arrayname [ rownum, columnnum ]
9. Output: NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
Output: (2, 4), which means that the array has 2 dimensions,
and each dimension has 4 elements.
10. Difference between NumPy Array and Python Lists
• NumPy is an alternative for lists in Python as it holds less
memory, has faster processing, and is more convenient to use.
•
• The difference between the elements is that the NumPy array
has to be homogenous. (All elements should be of the same
type)
• Arrays in NumPy are more compact when we compare it to
lists.
• NumPy arrays are stored at one continuous place in memory
• NumPy array supports vectorised operation, i.e., you need to pertorm any
function on every /element of a sequence one by one which is not supported
in Python lists.