Array in Python | Set 1 (Introduction and Functions)
Last Updated :
19 Sep, 2023
Other than some generic containers like lists, Python in its definition can also handle containers with specified data types. The array can be handled in Python by a module named "array". They can be useful when we have to manipulate only specific data type values.
Properties of Arrays
- Each array element is of the same data type and size. For example: For an array of integers with the int data type, each element of the array will occupy 4 bytes.
- Elements of the array are stored in contiguous memory locations.
Operations on Array in Python
Below are some operations that can be performed in an array:
- append()
- insert()
- pop()
- remove()
- index()
- reverse()
array(data type, value list) in Python
This function is used to create an array with data type and value list specified in its arguments. Some data types are mentioned in the table below.
|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | Py_UNICODE | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
Python append() Method
This function is used to add the value mentioned in its arguments at the end of the array. In this example, we are adding an element at the end of the array.
Python3
# importing "array" for array operations
import array
# initializing array with array values and signed integers
arr = array.array('i', [1, 2, 3])
# printing original array
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")
# using append() to insert new value at end
arr.append(4);
# printing appended array
print("The appended array is : ", end="")
for i in range (len(arr)):
print (arr[i], end=" ")
OutputThe new created array is : 1 2 3
The appended array is : 1 2 3 4
Array insert(i,x) Method in Python
This function is used to add the value(x) at the ith position specified in its argument. In this example, we are inserting an element at a specified index in an array.
Python3
# importing "array" for array operations
import array
# initializing array with array values and signed integers
arr = array.array('i', [1, 2, 3])
# printing original array
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
arr.insert(2, 5)
print("\r")
# printing array after insertion
print ("The array after insertion is : ", end="")
for i in range (len(arr)):
print (arr[i], end=" ")
OutputThe new created array is : 1 2 3
The array after insertion is : 1 2 5 3
Time Complexity: The initialization of the array takes O(n) time, where n is the number of elements in the array. The for loops used for printing the original array and the appended/inserted array takes O(n) time each, where n is the number of elements in the array. The append() method takes O(1) time as it adds the new element at the end of the array in constant time. The insert() method takes O(n) time in the worst case as it may have to shift all the elements to the right of the given position by one index, where n is the number of elements in the array. Therefore, the overall time complexity of the code is O(n) + O(n) + O(1) + O(n) = O(n).
Auxiliary Space: The array data structure used for initialization, append() and insert() methods requires a fixed amount of space for each element in the array. The space used by the print statements is negligible compared to the space used by the array. Therefore, the auxiliary space complexity of the code is O(n), where n is the number of elements in the array.
array pop() Method in Python
This function removes the element at the position mentioned in its argument and returns it. In this example, we are removing an element mentioned at a particular index.
Python3
# importing "array" for array operations
import array
# initializing array with array values
arr= array.array('i',[1, 2, 3, 1, 5])
# printing original array
print ("The new created array is : ",end="")
for i in range (0,5):
print (arr[i],end=" ")
print("\r")
# using pop() to remove element at 2nd position
print ("The popped element is : ",end="")
print (arr.pop(2));
# printing array after popping
print ("The array after popping is : ",end="")
for i in range (len(arr)):
print (arr[i],end=" ")
OutputThe new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
Array remove() in Python
This function is used to remove the first occurrence of the value mentioned in its arguments. In this example, we are removing the first occurrence of 1 from a given array.
Python3
# importing "array" for array operations
import array
# initializing array with array values
arr= array.array('i',[1, 2, 3, 1, 5])
# printing original array
print ("The new created array is : ",end="")
for i in range (0,5):
print (arr[i],end=" ")
print("\r")
# using remove() to remove 1st occurrence of 1
arr.remove(1)
# printing array after removing
print ("The array after removing is : ",end="")
for i in range (len(arr)):
print (arr[i],end=" ")
OutputThe new created array is : 1 2 3 1 5
The array after removing is : 2 3 1 5
Array index() Method
This function returns the index of the first occurrence of the value mentioned in the arguments. In this example, we are finding the index of 1st occurrence of 2 and printing it.
Python3
# importing "array" for array operations
import array
# initializing array with array values
arr= array.array('i',[1, 2, 3, 1, 2, 5])
# printing original array
print ("The new created array is : ",end="")
for i in range (0,6):
print (arr[i],end=" ")
print("\r")
# using index() to print index of 1st occurrence of 2
print ("The index of 1st occurrence of 2 is : ",end="")
print (arr.index(2))
OutputThe new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
Array reverse() Function
This function reverses the array. In this example, we are reversing the array by using reverse().
Python3
# importing "array" for array operations
import array
# initializing array with array values
arr= array.array('i',[1, 2, 3, 1, 2, 5])
# printing original array
print ("The new created array is : ",end="")
for i in range (0,6):
print (arr[i],end=" ")
print("\r")
#using reverse() to reverse the array
arr.reverse()
# printing array after reversing
print ("The array after reversing is : ",end="")
for i in range(len(arr)):
print (arr[i],end=" ")
OutputThe new created array is : 1 2 3 1 2 5
The array after reversing is : 5 2 1 3 2 1
Where can arrays be used?
- Arrays should be used where the number of elements to be stored is already known.
- Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched.
- Generally, when we require very fast access times, we usually prefer arrays since they provide O(1) access times.
- Arrays work well when we have to organize data in multidimensional format. We can declare arrays of as many dimensions as we want.
- If the index of the element to be modified is known beforehand, it can be efficiently modified using arrays due to quick access time and mutability.
Related Article: Array in Python | Set 2 (Important Functions)
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Types of Network Topology
Network topology refers to the arrangement of different elements like nodes, links, or devices in a computer network. Common types of network topology include bus, star, ring, mesh, and tree topologies, each with its advantages and disadvantages. In this article, we will discuss different types of n
12 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read