Python Arrays


Arrays are fundamental part of most programming languages. It is the collection of elements of a single data type, eg. array of int, array of string.
However, in Python, there is no native array data structure. So, we use Python lists instead of an array.
Note: If you want to create real arrays in Python, you need to use NumPy's array data structure. For mathematical problems, NumPy Array is more efficient.
Unlike arrays, a single list can store elements of any data type and does everything an array does. We can store an integer, a float and a string inside the same list. So, it is more flexible to work with.
[10, 20, 30, 40, 50 ] is an example of what an array would look like in Python, but it is actually a list.

Create an Array

We can create a Python array with comma separated elements between square brackets[].

Example 1: How to create an array in Python?

We can make an integer array and store it to arr.
arr = [10, 20, 30, 40, 50]

Access elements of an Array

We can access individual elements of an array using index inside square brackets [].

Array Index

Index is the position of element in an array. In Python, arrays are zero-indexed. This means, the element's position starts with 0 instead of 1.

Example 2: Accessing elements of array using indexing

arr = [10, 20, 30, 40, 50]
print(arr[0])
print(arr[1])
print(arr[2])
When we run the above program, the output will be:
10
20
30
Here, the first element of arr is arr[0], second is arr[1], third is arr[2], and so on.

Negative Indexing

Python programming supports negative indexing of arrays, something that is not available in arrays in most programming languages. This means the index value of -1 gives the last element, and -2 gives the second to last element of an array.

Example 3: Accessing elements of array using negative indexing

arr = [10, 20, 30, 40, 50]
print(arr[-1])
print(arr[-2])
When we run the above program, the output will be:
50
40

Find length of an Array

Python arrays are just lists, so finding the length of an array is equivalent to finding length of a list in Python.

Example 4: Find length of an array using len()

brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"]
num_brands = len(brands)
print(num_brands)
When we run the above program, the output will be:
5
As seen from the above example, the len function gives the length of array brands which is 5.

Add an element to an Array

To add a new element to an array, we use append() method in Python.

Example 5: Adding an element in an array using append()

add = ['a', 'b', 'c']
add.append('d')
print(add)
When we run the above program,the output will be
['a', 'b', 'c', 'd']
Here, we used append() method to add 'd'.

Remove elements from an Array

Python's list implementation of array allows us to delete any elements from an array using del operator.
Similarly, we can also use remove() and pop() methods to remove elements in an array.

Example 6: Removing elements of an array using del, remove() and pop()

colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
del color[4]
colors.remove("blue")
colors.pop(3)
print(color)
When we run the above program, the output will be
['violet', 'indigo', 'green', 'red']
In the above program,
  • First, we used del statement to remove element located at index 4, i.e. 'yellow'. Now, the colors array becomes ['violet', 'indigo', 'blue', 'green', 'orange', 'red'].
  • Then, we used remove('blue') function to remove element 'blue' from the array. Now the colors array becomes ['violet', 'indigo', 'green', 'orange', 'red'].
  • Then, we used pop(3) function to delete element at index 3, i.e. 'orange'. Finally, the colors array becomes ['violet', 'indigo', 'orange', 'red'] as shown in the output.

Modify elements of an Array

We can change values of elements within an array using indexing and assignment operator (=). We select the position of any element using indexing and use assignment operator to provide a new value for the element.

Example 7: Modifying elements of an array using Indexing 

fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
fruits[1] = "Pineapple"
fruits[-1] = "Guava"
print(fruits)
When we run the above program, the output will be:
['Apple', 'Pineapple', 'Mango', 'Grapes', 'Guava']
When we print the elements of fruits it shows that Pineapple replaced Banana at index 1.
We also changed last element of fruits to Guava, using negative indexing.
Thus, we can change and update the elements of array easily.

Python operators to modify elements in  an Array

In Python arrays, operators like +, * can also be used to modify elements.
We can use + operator to concatenate (combine) two arrays.

Example 8: Concatenating two arrays using + operator

concat = [1, 2, 3]
concat += [4,5,6]
print(concat)
When we run the above program. the output will be:
[1, 2, 3, 4, 5, 6]
Similarly, we can use * operator to repeat the elements multiple times.

Example 8: Repeating elements in array using * operator

repeat = ["a"]
repeat = repeat * 5
print(repeat)
When we run the above program, the output will be
['a', 'a', 'a', 'a', 'a']We repeated string "a" for 5 times, using * operator.

Slicing an Array

Python has a slicing feature which allows to access pieces of an array. We, basically, slice an array using a given range (eg. 2nd to 5th position), giving us elements we require. This is done by using indexes separated by a colon [x : y].
We can use negative indexing with slicing too.

Example 9: Slicing an array using Indexing

fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits[1:4])
print(fruits[ : 3])
print(fruits[-4:])
print(fruits[-3:-1])
When we run the above program, the output will be:
['Banana', 'Mango', 'Grapes']
['Apple', 'Banana', 'Mango']
['Banana', 'Mango', 'Grapes', 'Orange']
['Mango', 'Grapes']
While creating a slice [1:4], slicing starts (inclusive) with left index number, and slicing ends (exclusive) with right index number. This means slicing only prints out the elements of position 1, 2, and 3. Here, position 4 is exclusive so we don't get Orange as an output.
In the code fruits[:3], you can see we didn't include the index on the left. This means, slicing takes all elements until the index on the right (excluding the right index), i.e. first 3 (0, 1, 2) elements of the array.
Likewise, fruits[-4:] prints all elements after second position (1 or -4) i.e 'Banana'. This code is equivalent to fruits[1:].
In the final code, fruits[-3:-1], it all elements starting from index -3 to -2.

Python Array Methods

Other array operations are also available in Python using list/array methods given as:

Methods

Functions

append()
to add element to the end of the list
extend()
to extend all elements of a list to the another list
insert()
to insert an element at the another index
remove()
to remove an element from the list
pop()
to remove elements return element at the given index
clear()
to remove all elements from the list
index()
to return the index of the first matched element
count()
to count of number of elements passed as an argument
sort()
to sort the elements in ascending order by default
reverse()
to reverse order element in a list
copy()
to return a copy of elements in a list

Multidimensional arrays

All arrays created above are single dimensional. We can also create a multidimensional array in Python. A multidimensional array is an array within an array. This means an array holds different arrays inside it.

Example 10: Create a two-dimensional array using lists

multd = [[1,2], [3,4], [5,6], [7,8]]
print(multd[0])
print(multd[3])
print(multd[2][1])
print(multd[3][0])
When we run the above program, the output will be
[1, 2]
[7, 8]
6
7
Here, we have 4 elements and each elements hold another 2 sub-elements.

Read alsoPython Data Types
Thank you :)

Comments

Popular posts from this blog

Python Matrix

Angular : List of Topics

What are the steps involved in the concreting Process?