Browse by Domains

Python Array & How To Use Them [With Examples]

What is Python Array?

An array is defined as a collection of items sorted at contiguous memory locations. An array is like a container that holds similar types of multiple items together, this helps in making calculation easy and faster. The combination of arrays helps to reduce the overall size of the program. If you have a list of items that are stored in multiple variables, for example,

Animal1 = “Dog”
Animal2 = “Tiger”
Animal3 = “Lion”
Animal4 = “Elephant”
Animal5 = “Deer”

Then you can combine these all in a single variable in form of an array.

In python, the array can be handled by a module called “array”, which is helpful if we want to manipulate a single type of data value. Below are two important terms that can help in understanding the concept of an array.

  1. Element: Each item stored in an array is called an element.
  2. Index: The location of each element is defined by a numerical value called index. Each element in an array has an index value by which it can be identified.

Array Representation

The array can be declared in multiple ways depending upon the programming language we are using. But few points are important that need to consider while working with an array:

  1. The starting index of an array is 0
  2. Each element in an array is accessible by its index
  3. The length or size of an array determines the capacity of the array to store the elements

The syntax for Array Representation

arrayName = array.array (dataType, [array,items])

Creating Python Array

In Python, the array can be created by importing the array module. You can now create the array using array.array(). Instead of using array.array() all the time, you can use “import array as arr”, the arr will work as an alias and you can create an array using arr.array(). This alias can be anything as per your preference.

variable_name = array(typecode, [value_list])

For Example:

import array as arr
myarray = arr.array ( ‘i’, [1, 2, 3, 4, 5])

In the above code, the letter ‘i’ represents the type code and the value is of integer type.

The below tables show the type codes:

Type codePython typeC TypeMin size(bytes)
‘u’Unicode characterPy_UNICODE2
‘b’IntSigned char1
‘B’IntUnsigned char1
‘h’IntSigned short2
‘l’IntSigned long4
‘L’IntUnsigned long4
‘q’IntSigned long long8
‘Q’IntUnsigned long long8
‘H’IntUnsigned short2
‘f’FloatFloat4
‘d’FloatDouble8
‘i’IntSigned int2
‘I’IntUnsigned int2

Accessing Python Array Elements

We can access the Array elements by using its index. The index is always an integer.

Syntax: variable_name [index_number]

Example:

import array as ar
height = ar.array (‘i’ , [165, 166, 154, 176, 144])
print (height[3])
print (height[0])

Output:

176

165

 

The above figure represents the array element and its indexing. In array, the indexing starts with 0, so as per the example the value at height[3] is 176 and the value at height[0] is 165.

Remember the last index of an array is always one less than the length of an array. If n is the length of an array then n-1 will be the last index of that array.  

In Python, you can access the element using negative indexing such as the last element of an array will have the index -1, the second last element will have index -2, and so on. 

Example:

import array as ar
height = ar.array (‘i’ , [165, 166, 154, 176, 144])
print (height[-3])
print (height[-1])

Output:

154

144

Slicing Python Arrays

The slicing operator “ : “ helps to access the range of elements in an array.

Example:

import array as ar
value = ar.array (‘i’, [5, 2, 7, 1, 34, 54, 22, 7, 87, 2¸ 53, 22, 0, 11])  
print (value [1:5])
print (value [7:])
print (value [:])
print (value [:-5])

Output :

array (‘i’ , [2, 7, 1, 34])

array (‘i’ , [22, 7, 87, 2¸ 53, 22, 0, 11])

array (‘i’ , [5, 2, 7, 1, 34, 54, 22, 7, 87, 2¸ 53, 22, 0, 11])

array (‘i’ , [5, 2, 7, 1, 34, 54, 22, 7, 87])

Changing and Adding Elements 

Lists are mutable which means we can change and add the elements after the lists have been defined. Let’s first see how we can change the elements from the lists.

Changing List Elements

If we want to change a single element in a list we can change it by using its index. Let’s see the approach for the same.

my_list [0] = value

my_list [4] = value

In the above statements, we are changing the value of the element present at index 0 and at index 4. This will replace the old element with the new element. The value defines the new element that we want to enter into the list.

Example

import array as arr
list = arr.array(‘i', [2, 5, 6, 2, 6 ,1, 7, 8, 12, 45, 4]
list [0] = 111
list [4] = 232
list [-1] = 0
print (list)

Output

array(‘i’ [111, 5, 6, 2, 232, 1, 7, 8, 12, 45, 0])

If we want to change all the items in a list with an increment or decrement in the values then we can change all the elements present in a list.

Example

import array as arr
list = arr.array(‘i', [2, 5, 6, 2, 6 ,1, 7, 8, 12, 45])
print ("Original List")
print (list)
print ("Updated List")
list = [i+5 for i in list]
print (list)

Output

Original List

arr.array(‘i’, [2, 5, 6, 2, 6, 1, 7, 8, 12, 45])

Updated List

array(‘i’, [7, 10, 11, 7, 11, 6, 12, 13, 17, 50])

In the above example, we have incremented the value of the list by 5 using one single line. This method is known as a list comprehension.

Adding List Elements

We can add elements to lists in three ways:

  1. append() : append() method can add single element or an object in a list.

Syntax : list.append (value)

Example

>>>import array as arr
>>> list = arr.array(‘i', [2, 5, 6, 2, 6, 1, 7, 8, 12, 45])
>>> list.append (100)
>>> print (list)

Output

array(‘i’, [2, 5, 6, 2, 6, 1, 7, 8, 12, 45, 100])

In the above example, we have added a new value of 100 to the existing list. The new appended value will be added to the last in the list.

We can also append one list into another list using the append() method.

Example

>>>import array as arr
>>> list_first = arr.array(‘i', [5, 10, 15, 20])
>>> list_second = arr.array(‘i', [2, 4, 6, 8])
>>> list_first.append (list_second)
>>> print (list_first)

Output

array(‘i’, [5, 10, 15, 20, [2, 4, 6, 8]])

In above example we have appended the second list values in first list. Here second list acts as a single object. 

  1. insert() : insert() method inserts the element at a specific position

Syntax : list.insert ( index_value , element)

Example

>>>import array as arr
>>> list_first = arr.array(‘i', [5, 10, 15, 20])
>>> list_first.insert (0, 1)
>>> print (list_first)

Output

array(‘i’, [1, 5, 10, 15, 20])

In the above example, we have inserted the value 1 at index 0.

  1. extend(): extend() method helps to add multiple elements at the end of the lists at the same time.

Both append() and extend() add elements at the end of the list, but extend() can add multiple elements together with is not possible in append().

Syntax : list.extend ([value1, value2, value3, ….. ])

Example

import array as arr
list = arr.array(‘i', [2, 5, 6, 2, 6 ,1])
print ("Original List")
print (list)

print ("Updated List")
list.extend arr.array(‘i', ([39, 239]))
print (list)

Output

Original List

array(‘i’, [2, 5, 6, 2, 6, 1])

Updated List

array(‘i’, [2, 5, 6, 2, 6, 1, 39, 239])

Removing Python Array Elements

We can remove elements from an array using three methods, let’s see each of them with examples.

  1. remove(): The remove() method will remove only the first occurrence of an item. That means if the same items are present multiple times in a list the remove() method will only remove the first occurrence of that item.

Syntax: list.remove (value) 

Example  

color = arr.array(‘i', [2, 5, 3, 7, 8, 2, 1 ])
color.remove( 2 )
print( color )

Output

array(‘i’, [5, 3, 7, 8, 2, 1])

  1. pop(): pop() method is another method to remove elements from the lists. It performs the same tasks as the remove() method, but the only difference is that the remove() method takes the value as an argument, and the pop() method accepts the index as an argument. We need to give the index as an argument and the pop() method will pop out the value present at that particular index. The pop() method returns the value present at that index.

Syntax : list.pop (index_value)

Example

>>> color = arr.array(‘i', [2, 5, 3, 7, 8, 2, 1 ])
>>> color.pop(4)
>>> print(color)

Output

8

array(‘i’, [2, 5, 3, 7, 2, 1])

In the above example, the pop() method deletes the elements present at index 4 and returns the value present on that index that is ‘Blue’

The pop() method raises “IndexError” if the index specified is out of range.

  1. del: The del operator is similar to the pop() method with one important difference. The del method takes the index as an argument and remove that element from the list but does not return any value. But the pop() method returns the value present at that index. Similar to the pop() method, del also raises “IndexError” if the index or the indices specify are out of range.

Syntax : del list (index_value)

Example

>>> color = arr.array(‘i', [2, 5, 3, 7, 8, 2, 1 ])
>>> del color[5]
>>> print(color)

Output

array(‘i’, [2, 5, 3, 7, 8, 1 ])

Python Lists vs Array

ArrayLists
An array can store similar types of data elementsThe list can store different types of data elements
Need to import a module explicitly for declarationNo need to import a module explicitly for declaration
An array is more compatible than a listLists are less compatible than arrays to store the data
We can print the array elements without using explicit loopingWe can print the entire list using explicit looping
Array consumes less memory size Lists consume more memory size for easy addition 
An array is preferred when we need to store a large amount of dataLists are preferred when we need to store a shorter sequence of data
An array can handle arithmetic operations directlyThe list cannot handle arithmetic operations directly
In array, it must contain either all nested elements of the same sizeThe list can be nested to have different kinds of elements

When to Use Array?

An array is useful when we want to use many variables of the same type. It helps to allocate memory dynamically and saves memory. With the use of arrays, we can easily implement linked lists, stacks, queues, graphs, trees, etc.

An array is used while implementing sorting algorithms such as bubble sort, insertion sort, selection sort, etc. We can make use of an array to store elements. An array is also used for CPU scheduling and performing matrix operations. 

Why use Array in Python?

Array helps to save time. We can store a large amount of data without declaring separate integers of each number or element. With the help of Python, we can reduce the lines of code. An array is useful in implementing data structures such as stack, queue, linked list, etc. Array performs great numerical operations where the list cannot directly handle the math operations. 

Array are mutable which means we can change the elements of an array whenever needed, therefore we can perform various manipulation whenever required.

Finding Length of an Array

To find the exact numbers of elements in an array we can use the built-in method len(). This method is used to specify the total number of elements in an array.

Example 

>>> import array as ar
>>> length = ar.array ('i', [3, 5, 1, 7, 0])
>>> print (len(length))

Output

5

In the above example, the total number in an array is 5 so the length of the array is 5.

Array Concatenation

In array concatenation, we use concatenate arrays with the help of the symbol “+”.

Example

>>> import array as ar
>>> first = ar.array ('i', [3, 5, 1, 7, 0])
>>> second = ar.array ('i', [12, 16, 19, 20])
>>> add = ar.array ('i')
>>> add = first + second
>>> print ( " Concatenated Array = ", add)

Output

Concatenated Array = array(‘i’, [3, 5, 1, 7, 0, 12, 16, 19, 20])

In the above example, we have concatenated two arrays into a single array. As we know array holds a similar type of values so the concatenated values should be of the same type. 

Conclusion

So we have seen how we can use arrays in python and also came to know all the basic manipulation we can do on arrays. So, this brings us to the end of our article Python Array.

Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top