Python 3-Arrays

Python Arrays

Arrays are used to store multiple values in one single variable. The array values can be accessed through index of the stored variable.

Example:

input_array = ["apple", "banana", "strawberry"]
print(input_array[0])

Output:

Apple

From the above example,

  • Above prints the 0th index of the array. Hence, the last number of array with n elements will be n-1
  • Looping the data in array can be done using “for” loop.

Functions used with arrays:

Append -> this helps to append value at the end of an array.

input_array.append("mango")
print(input_array)

Output:

['apple', 'banana', 'strawberry', 'mango']

Extend -> it help us to append more than one elements in array or append another array with the existing one.

input_array = ['apple', 'banana', 'strawberry', 'mango']
a = ["cranberry", "blueberry", "orange"]
input_array.extend(a)
print(input_array)

Output:

 ['apple', 'banana', 'strawberry', 'mango', 'cranberry', 'blueberry', 'orange']

Pop -> this helps to pop the last element in the array

Example:

input_array = ['apple', 'banana', 'strawberry', 'mango']
input_array.pop()

Output:

‘mango’

Remove-> helps to remove the element from the array. If there are duplicate elements in the array which you are trying to remove, it removes the first occurring element in the array.

Example:

a = [1, 2, 3, 4, 4, 4, 5]
a.remove(4)
print(a)

Output:

[1, 2, 3, 4, 4, 5]

Similarly, we have many such functions in array operations such as

  • Sort()-> sort the array in ascending order.
  • Insert() -> it helps to insert the element by mentioning the exact position
  • Copy() -> to copy the array into another array.
  • Index() -> to find the index of the particular element in the array
  • Count()-> to count the repeated elements in the array
  • Reverse()-> reverse the entire array into backward
  • Clear()-> to clear all the elements in the array but will not delete the array itself.