Accessing array elements in python


Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.


Arrays

Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library.

Arrays are used to store multiple values in one single variable:

Example

Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

Try it Yourself »


What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.


Access the Elements of an Array

You refer to an array element by referring to the index number.

Example

Modify the value of the first array item:

cars[0] = "Toyota"

Try it Yourself »


The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example

Return the number of elements in the cars array:

x = len(cars)

Try it Yourself »

Note: The length of an array is always one more than the highest array index.



Looping Array Elements

You can use the for in loop to loop through all the elements of an array.


Adding Array Elements

You can use the append() method to add an element to an array.

Example

Add one more element to the cars array:

cars.append("Honda")

Try it Yourself »


Removing Array Elements

You can use the pop() method to remove an element from the array.

You can also use the remove() method to remove an element from the array.

Example

Delete the element that has the value "Volvo":

cars.remove("Volvo")

Try it Yourself »

Note: The list's remove() method only removes the first occurrence of the specified value.


Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

MethodDescription
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.



W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2022 by Refsnes Data. All Rights Reserved.
W3Schools is Powered by W3.CSS.

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type. 
 

Accessing array elements in python

 

Creating a Array

Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments. 
 

Python3

import array as arr

a = arr.array('i', [1, 2, 3])

print ("The new created array is : ", end =" ")

for i in range (0, 3):

    print (a[i], end =" ")

print()

b = arr.array('d', [2.5, 3.2, 3.3])

print ("The new created array is : ", end =" ")

for i in range (0, 3):

    print (b[i], end =" ")

Output : 

The new created array is :  1 2 3 
The new created array is :  2.5 3.2 3.3 

Complexities for Creation of Arrays:

Time Complexity: O(1)

Auxiliary Space: O(n)

Some of the data types are mentioned below which will help in creating an array of different data types. 
 

Accessing array elements in python

Adding Elements to a Array

Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the array. 
 

Python3

import array as arr

a = arr.array('i', [1, 2, 3])

print ("Array before insertion : ", end =" ")

for i in range (0, 3):

    print (a[i], end =" ")

print()

a.insert(1, 4)

print ("Array after insertion : ", end =" ")

for i in (a):

    print (i, end =" ")

print()

b = arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")

for i in range (0, 3):

    print (b[i], end =" ")

print()

b.append(4.4)

print ("Array after insertion : ", end =" ")

for i in (b):

    print (i, end =" ")

print()

Output : 

Array before insertion : 1 2 3 
Array after insertion :  1 4 2 3 
Array before insertion : 2.5 3.2 3.3 
Array after insertion :  2.5 3.2 3.3 4.4 

Complexities for Adding elements to the Arrays:

Time Complexity: O(1)/O(n) ( O(1) – for inserting elements at the end of the array, O(n) – for inserting elements at the beginning of the array and to the full array

Auxiliary Space: O(1)
 

Accessing elements from the Array

In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer. 
 

Python3

import array as arr

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

print("Access element is: ", a[0])

print("Access element is: ", a[3])

b = arr.array('d', [2.5, 3.2, 3.3])

print("Access element is: ", b[1])

print("Access element is: ", b[2])

Output : 

Access element is:  1
Access element is:  4
Access element is:  3.2
Access element is:  3.3

Complexities for accessing elements in the Arrays:

Time Complexity: O(1)

Auxiliary Space: O(1)
 

Removing Elements from the Array

Elements can be removed from the array by using built-in remove() function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the searched element. 
 

Python3

import array

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

print ("The new created array is : ", end ="")

for i in range (0, 5):

    print (arr[i], end =" ")

print ("\r")

print ("The popped element is : ", end ="")

print (arr.pop(2))

print ("The array after popping is : ", end ="")

for i in range (0, 4):

    print (arr[i], end =" ")

print("\r")

arr.remove(1)

print ("The array after removing is : ", end ="")

for i in range (0, 3):

    print (arr[i], end =" ")

Output: 

The new created array is : 1 2 3 1 5 
The popped element is : 3
The array after popping is : 1 2 1 5 
The array after removing is : 2 1 5 

Complexities for Removing elements in the Arrays:

Time Complexity: O(1)/O(n) ( O(1) – for removing elements at the end of the array, O(n) – for removing elements at the beginning of the array and to the full array

Auxiliary Space: O(1)
 

Slicing of a Array

In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. 
 

Accessing array elements in python

Python3

import array as arr

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)

print("Initial Array: ")

for i in (a):

    print(i, end =" ")

Sliced_array = a[3:8]

print("\nSlicing elements in a range 3-8: ")

print(Sliced_array)

Sliced_array = a[5:]

print("\nElements sliced from 5th "

      "element till the end: ")

print(Sliced_array)

Sliced_array = a[:]

print("\nPrinting all elements using slice operation: ")

print(Sliced_array)

Output

Initial Array: 
1 2 3 4 5 6 7 8 9 10 
Slicing elements in a range 3-8: 
array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end: 
array('i', [6, 7, 8, 9, 10])

Printing all elements using slice operation: 
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Searching element in a Array

In order to search an element in the array we use a python in-built index() method. This function returns the index of the first occurrence of value mentioned in arguments. 
 

Python3

import array

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

print ("The new created array is : ", end ="")

for i in range (0, 6):

    print (arr[i], end =" ")

print ("\r")

print ("The index of 1st occurrence of 2 is : ", end ="")

print (arr.index(2))

print ("The index of 1st occurrence of 1 is : ", end ="")

print (arr.index(1))

Output: 
 

The new created array is : 1 2 3 1 2 5 
The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0

 Complexities for searching elements in the Arrays:

Time Complexity: O(n)

Auxiliary Space: O(1)
 

Updating Elements in a Array

In order to update an element in the array we simply reassign a new value to the desired index we want to update. 
 

Python3

import array

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

print ("Array before updation : ", end ="")

for i in range (0, 6):

    print (arr[i], end =" ")

print ("\r")

arr[2] = 6

print("Array after updation : ", end ="")

for i in range (0, 6):

    print (arr[i], end =" ")

print()

arr[4] = 8

print("Array after updation : ", end ="")

for i in range (0, 6):

    print (arr[i], end =" ")

Output:

Array before updation : 1 2 3 1 2 5 
Array after updation : 1 2 6 1 2 5 
Array after updation : 1 2 6 1 8 5 

Complexities for updating elements in the Arrays:

Time Complexity: O(n)

Auxiliary Space: O(1)
 


How do you access elements in an array?

Array elements are accessed by using an integer index. Array index starts with 0 and goes till the size of the array minus 1. The name of the array is also a pointer to the first element of the array.

How do you access the elements of a NumPy array?

You can access an array element 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.

How do I display all array elements in Python?

STEP 1: Declare and initialize an array. STEP 2: Loop through the array by incrementing the value of i. STEP 3: Finally, print out each element of the array.

How do you access an array of strings in Python?

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.