Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:
- Dynamic Typing:Python lists can hold elements of different types in the same list. We can have an integer, a string and even other lists all stored within a single list.
- Dynamic Resizing:Lists are dynamically resized, meaning you can add or remove elements without declaring the size of the list upfront.
- Built-in Methods: Python lists come with numerous built-in methods that allow for easy manipulation of the elements within them, including methods for appending, removing, sorting and reversing elements.
Example:
Pythona=[1,"Hello",[3.14,"world"]]a.append(2)# Add an integer to the endprint(a)
Output[1, 'Hello', [3.14, 'world'], 2]
Note:Pythondoes not have built-in array support in the same way that languages like C and Java do, but it provides something similar through the array module for storing elements of a single type.
NumPy Arrays
NumPy arrays are a part of theNumPy library, which is a powerful tool for numerical computing in Python. These arrays are designed for high-performance operations on large volumes of data and support multi-dimensional arrays and matrices. This makes them ideal for complex mathematical computations and large-scale data processing.
Key Features:
- Multi-dimensional support: NumPy arrays can handle more than one dimension, making them suitable for matrix operations and more complex mathematical constructs.
- Broad broadcasting capabilities: They can perform operations between arrays of different sizes and shapes, a feature known as broadcasting.
- Efficient storage and processing:NumPy arrays are stored more efficiently than Python lists and provide optimized performance for numerical operations.
Example Code:
Pythonimportnumpyasnp# Creating a NumPy arrayarr=np.array([1,2,3,4])# Element-wise operationsprint(arr*2)# Multi-dimensional arrayarr2d=np.array([[1,2],[3,4]])print(arr2d*2)
Output[2 4 6 8][[2 4] [6 8]]
Note:Choose NumPy arrays for scientific computing, where you need to handle complex operations or work with multi-dimensional data.
Use Python's array module when you need a basic, memory-efficient container for large quantities of uniform data types, especially when your operations are simple and do not require the capabilities of NumPy.
Python Arrays
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. UnlikePython 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:
Pythonimportarrayasarr# creating array of integersa=arr.array('i',[1,2,3])# accessing First Araayprint(a[0])# Adding element to arraya.append(5)print(a)
Output1array('i', [1, 2, 3, 5])
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.
Pythonimportarrayasarr# creating arraya=arr.array('i',[1,2,3])# iterating and printing each itemforiinrange(0,3):print(a[i],end=" ")
Python Array IndexAdding Elements to an Array
Elements can be added to the Python Array by using built-ininsert()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.
Pythonimportarrayasarr# Integer array examplea=arr.array('i',[1,2,3])print("Integer Array before insertion:",*a)a.insert(1,4)# Insert 4 at index 1print("Integer Array after insertion:",*a)
OutputInteger Array before insertion: 1 2 3Integer Array after insertion: 1 4 2 3
Note: We have used *a and *b forunpacking 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.
Pythonimportarrayasarra=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])
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.
Pythonimportarrayarr=array.array('i',[1,2,3,1,5])# using remove() method to remove first occurance of 1arr.remove(1)print(arr)# pop() method - remove item at index 2arr.pop(2)print(arr)
Outputarray('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.

- 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].
Pythonimportarrayasarrl=[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)
Outputarray('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.
Pythonimportarrayarr=array.array('i',[1,2,3,1,2,5])# index of 1st occurrence of 2print(arr.index(2))# index of 1st occurrence of 1print(arr.index(1))
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.
Pythonimportarrayarr=array.array('i',[1,2,3,1,2,5])# update item at index 2arr[2]=6print(arr)# update item at index 4arr[4]=8print(arr)
Outputarray('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 usecount() method to count given item in array.
Pythonimportarrayarr=array.array('i',[1,2,3,4,2,5,2])count=arr.count(2)print("Number of occurrences of 2:",count)
OutputNumber 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.
Pythonimportarrayarr=array.array('i',[1,2,3,4,5])arr.reverse()print("Reversed array:",*arr)
OutputReversed 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
Pythonimportarrayasarra=arr.array('i',[1,2,3,4,5])# using extend() methoda.extend([6,7,8,9,10])print(a)
Outputarray('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Quiz:
Related Articles:
Recommended Problems:
More Information Resource Related to Python Array:
Suggested Quiz
10 Questions
Which of the following is the correct way to create an array in Python using the array module?
array = array('i', [1, 2, 3])
Explanation:
array
module in Python is used to create an array, which is different from lists
What is the output of the following code?
Pythonfromarrayimportarrayarr=array('i',[1,2,3,4,5])print(arr[0])
Explanation:
Unlike Python’s built-in list, thearray module is forhomogeneous arrays(all elements must be of the same type) hence'i'denotes "unsigned integers" and then accessing the first element of the array returns the value 1.
Which of the following methods is used to add an element to the end of an array?
Explanation:
The append method adds an element to the end of the array.
What will be the output of the following code?
Pythonfromarrayimportarrayarr=array('i',[1,2,3])arr.insert(1,4)print(arr)
What does the index method do in an array?
Returns the last occurrence of a specified value
Inserts a value at a specified position
Returns the index of the first occurrence of a specified value
Removes an element at a specified position
Explanation:
The index method returns the index of the first occurrence of a specified value.
How to create an empty array of integers in Python using the array module?
Explanation:
Both array('i') and array('i', []) can be used to create an empty array of integers.
What does the following code print?
Pythonfromarrayimportarrayarr=array('i',[1,2,3])arr[1]=5print(arr)
Explanation:
Assigning a new value to an element at a specific index updates the array.
What is the result of the following code?
Pythonfromarrayimportarrayarr1=array('i',[1,2,3])arr2=array('i',[4,5])arr1+=arr2print(arr1)
array('i', [1, 2, 3, 4, 5])
array('i', [4, 5, 1, 2, 3])
array('i', [1, 2, 3, 9, 10])
Explanation:
The += operator concatenates two arrays of the same type.
What is the time complexity of accessing an element in an array by index?
Explanation:
Accessing an element by index in an array takes constant time, O(1).
Which of the following operations is not allowed on a Python array?
Accessing an element by index
Adding elements of different types
Iterating through elements
Explanation:
Python arrays created using the array module can only store elements of the same type.
Quiz Completed Successfully
Your Score : 2/10
Accuracy : 0%
Login to View Explanation
1/101/10< Previous Next >