The Wayback Machine - https://web.archive.org/web/20241225113747/https://www.geeksforgeeks.org/python-arrays/
Open In App

Python Arrays

Last Updated : 16 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Unlike Python lists (can store elements of mixed types), arrays must have all elements of same type. Having only homogeneous elements makes it memory-efficient.

Python Array Example

Python
import array as arr

# creating array of integers
a = arr.array('i', [1, 2, 3])

# accessing First Araay
print(a[0])

# Adding element to array
a.append(5)
print(a)  

Output
1
array('i', [1, 2, 3, 5])



To get a detailed explanation of Python Array go through the Python Self Paced course , this course offers you a complete fundamental of Python Array.


Create an Array in Python

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

Python
import array as arr

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

# iterating and printing each item
for i in range(0, 3):
    print(a[i], end=" ")

Output
1 2 3 

CommonArticleDesign1-min

Python Array Index


Adding Elements to an Array

Elements can be added to the Python 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 Python array.

Python
import array as arr

# Integer array example
a = arr.array('i', [1, 2, 3])
print("Integer Array before insertion:", *a)

a.insert(1, 4)  # Insert 4 at index 1
print("Integer Array after insertion:", *a)

Output
Integer Array before insertion: 1 2 3
Integer Array after insertion: 1 4 2 3

Note: We have used *a and *b for unpacking the array elements.

Accessing Array Items

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

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

print(a[0])
print(a[3])

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

Output
1
4
3.2
3.3

Removing Elements from the Array

Elements can be removed from the Python array by using built-in remove() function. It will raise an Error if element doesn’t exist. Remove() method only removes the first occurrence of the searched element. To remove range of elements, we can use an iterator.

pop() function can also be used to remove and return an element from the array. By default it removes only the last element of the array. To remove element from a specific position, index of that item is passed as an argument to pop() method.

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

# using remove() method to remove first occurance of 1
arr.remove(1)
print(arr)

# pop() method - remove item at index 2
arr.pop(2)
print(arr)

Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])


Slicing of an 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 .

CommonArticleDesign3-min


  • Elements from beginning to a range use [:Index]
  • Elements from end use [:-Index]
  • Elements from specific Index till the end use [Index:]
  • Elements within a range, use [Start Index:End Index]
  • Print complete List, use [:].
  • For Reverse list, use [::-1].
Python
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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


Sliced_array = a[3:8]
print(Sliced_array)

Sliced_array = a[5:]
print(Sliced_array)

Sliced_array = a[:]
print(Sliced_array)

Output
array('i', [4, 5, 6, 7, 8])
array('i', [6, 7, 8, 9, 10])
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Searching Element in an 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.


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

# index of 1st occurrence of 2
print(arr.index(2))

# index of 1st occurrence of 1
print(arr.index(1))

Output
1
0


Updating Elements in an Array

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

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

# update item at index 2
arr[2] = 6
print(arr)

# update item at index 4
arr[4] = 8
print(arr)

Output
array('i', [1, 2, 6, 1, 2, 5])
array('i', [1, 2, 6, 1, 8, 5])

Different Operations on Python Arrays

Counting Elements in an Array

We can use count() method to count given item in array.

Python
import array

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

print("Number of occurrences of 2:", count)

Output
Number of occurrences of 2: 3

Reversing Elements in an Array

In order to reverse elements of an array we need to simply use reverse method.

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

arr.reverse()
print("Reversed array:", *arr)

Output
Reversed array: 5 4 3 2 1


Extend Element from Array

In Python, an array is used to store multiple values or elements of the same datatype in a single variable. The extend() function is simply used to attach an item from iterable to the end of the array. In simpler terms, this method is used to add an array of values to the end of a given or existing array.

list.extend(iterable)

Here, all the element of iterable are added to the end of list1

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

# using extend() method
a.extend([6,7,8,9,10])
print(a)

Output
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])


Python Array – FAQs

What are Python Arrays?

Python Arrays are a data structure that can hold a collection of items. Unlike lists, which can hold items of different data types, arrays in Python are typically used to store items of the same data type. This makes them more efficient for numerical computations. Python does not have a built-in array data type, but the ‘array’ module provides an array type that can be used for this purpose.

How to create an Array in Python?

To create an array in Python, you can use the ‘array’ module. First, you need to import the module, and then you can create an array by specifying the type code and the initial values. For example: “`python import array arr = array.array(‘i’, [1, 2, 3, 4]) # ‘i’ indicates an array of integers “` This creates an array of integers with the values 1, 2, 3, and 4.

What is the difference between Lists and Arrays in Python?

The main difference between lists and arrays in Python is that lists can hold items of different data types, while arrays are designed to hold items of the same data type. Arrays are more memory efficient and provide better performance for numerical operations. However, lists are more flexible and easier to use for general-purpose programming.

How to access array elements in Python?

You can access elements in a Python array using indexing, similar to how you would access elements in a list. The index starts at 0 for the first element. For example: “`python import array arr = array.array(‘i’, [1, 2, 3, 4]) element = arr[2] # Accessing the third element print(element) # Output: 3 “`

Can you resize a Python Array?

Python arrays do not support dynamic resizing like lists do. However, you can create a new array with a different size and copy the elements from the old array to the new one. Alternatively, you can use the ‘array’ module’s ‘extend’ method to add more elements to the existing array, but this does not change the size of the array itself.




Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg