Python Arrays

An arrangement of objects or numbers in defined rows or columns is called an array in computer science. In other terms, we can define arrays as the collection of similar data types at adjoining memory locations in a language. Arrays are mainly used to describe mathematical concepts, generally, matrices form. Similarly, python arrays perform similar tasks handled by a module called an array. Arrays make it very easy for the user to calculate the position of elements in the list. This is simply done by setting an offset base value which is the memory location of the first element present in the arrays. For an instance, let us suppose some children are standing on the staircase where each child has taken up one stair. The location of any of the children can be determined by just counting the steps they are standing on.

Creating an Array in Python

An array is created by using the array module as an array(data_type,value_list) in python. Here, the value list is specified in the arguments. The index of an array always starts with 0 and every element is accessed in an array using the index only. Only the length of an array can define the capacity to store the elements. 

Below is a basic syntax to define arrays containing fruit names in python:


Fruits = ["Apple", "Banana", "Mango"]


The python program for the same will be written as:


Fruits = ["Apple", "Banana", "Mango"]

Print (Fruits);

Output:


['Apple', 'Banana', 'Mango']


An array is able to hold more than one value at a time. If a user has to store a list, say for example fruits, it can be written as:

Fruit1 = “Apple”

Fruit2 = “Banana”

Fruit3 = “Mango”


Below is a program to understand how a user can fetch an item to the index number:


Fruits = ["Apple", "Banana", "Mango"]

x = Fruits[0]

print (x);

Apple

Array Functions in Python


1. Length of an array: This method returns the number of elements present in the array. The user can use len() to calculate the length of an array

Below is a python code to calculate the length of the array:


Fruits = ["Apple", "Banana", "Mango"]

x = len(Fruits)

print (x);

Output:

3


In the python code above, len() function is calculating the length of the array. Hence it returns the length of the list as 3.

Become a Python Certified professional by learning this HKR Python Training!

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

2. Inserting an array element: This method adds an element to the array list. The user can use append() to perform insertion in an array. 

Below is a python code to insert an element in the array:

 

Fruits = ["Apple", "Banana", "Mango"]

Fruits.append("Cherry")

print (Fruits);


Output:

['Apple', 'Banana', 'Mango', 'Cherry']


In the python code above, ‘cherry’ is being added in the fruits list. Hence the array is returned as an updated list which will include cherry in the previous list.

3. Deleting an array element: This method removes an element from the array list. The user can use remove() to perform single item deletion in an array. In-case the user wants to remove a range of elements, pop() method is used instead of remove(). 
 

Below is a python code to remove the second element from the array:

 

Fruits = ["Apple", "Banana", "Mango"]

Fruits.pop(1)

print (Fruits);


Output:

['Apple', 'Mango']


In the python code above, the element at index 1 is being removed from the list. Hence the array will be returned without that specified removed element. 

NOTE: Here we use pop(1) and not pop(2) for the second element as the array index always starts from 0.  


4. Looping array elements: This can be performed using for-in loop to loop all the elements of the array.
 

Below is a python code to add a loop in the array:


Fruits = ["Apple", "Banana", "Mango"]

for x in Fruits:

  print(x)




Output:

Apple

Banana

Mango

5. Slicing an array: This method is used to print to the whole array except a range of array elements that the user does not want in the output. The sliced array is passed like this: [start:end]
 

Below is a python code to understand slicing in the array:


import numpy as np

array = np.array([1, 2, 3, 4, 5, 6, 7])


print(array[1:5])





Output:

[2 3 4 5]

As in the python code above, the user has mentioned that he only wants elements in the range of 1:5 as an output. Hence elements 6,7 are sliced out.

Top 30 frequently asked Python Interview Questions!

Subscribe to our youtube channel to get new updates..!

6. Searching an element in array: We use this method to search an element from the list of array. It is done by index() method. The method will return the index of the first presence of the element value in the argument. 

Below is a python code to perform searching of elements in the array:


from array import *

arr = array('i', [1,2,3,4,5])

print (arr.index(4))




Output:

3


If the given input value is absent in the array list, then the program will return output as an error.


7. Updating an array: This operation is used to update an existing array list at a specified index by the user.

Below is a python code to update operation amongst elements in the array:


from array import *

arr = array('i', [1,2,3,4,5])

arr[2] = 8

for a in arr:

 print(a)




Output:

1

2

8

4

5

As the user will compile and execute the above program, it will producesthe result which depicts  the new value at the index position 2 as mentioned. 


More Methods in Python

1.clear(): Removes all the elements from the array list
2.count(): Counts and returns the number of elements
3.copy(): Returns a copy of the array list 
4.extend(): Add the element of second list to the end of current list
5.insert(): Adds an element to the specified position of array list
6.index(): Returns the index of the fist element
7.pop(): Removes an element from the array list at a specific position
8.sort(): Performs sorting and then returns the list
9.traverse(): Prints all the elements of the array one by one

Typecodes in Arrays


Typecode                                                    Value


  B                                        unsigned integer of size 1 byte

  b                                         signed integer of size 1 byte

  c                                          character of size 1 byte

  i                                            signed integer of size 2 byte

  l                                            unsigned integer of size 2 byte

  f                                             floating point of size 4 byte

  d                                             floating point of size 8 byte


Python Lists v/s Arrays

This is a very interesting concept in python. The user is able to use python lists as arrays also. However, a user cannot fix the type of elements stored in a list. The array.array type is just a cover-like structure that provides space-efficient storage of basic data types. If the user feels that he should allocate the array he knows won't change, then arrays will be much faster as compared to lists and hence will utilize less memory than them. 

If you want to Explore more about Python? then read our updated article - Python Tutorial!

Python Training Certification

Weekday / Weekend Batches

Conclusion:

  • Arrays are the collection of similar data types at adjoining memory locations
  • An array is created by using the array module as an array(data_type,value_list)
  • The index of an array always starts with 0.
  • If the array length is 8, it means it can store a total of 8 elements.
  • An array can only be created in python by importing the array module in the python code
  • Array in Python has a number of important operations such as insertion, deletion, updating, searching, slicing, etc
  • The use of arrays in python is very easy and efficient

Related Articles

1. Python Generators

2. Python Ogre

3. Python IDEs

4. Python Training in Delhi

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 8th Jun 2023, Weekday batch

  • Batch starts on 12th Jun 2023, Weekday batch

  • Batch starts on 16th Jun 2023, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.