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
Array in Python | Set 2 (Important Functions)
Array in Python | Set 1 (Introduction and Functions)Array in Python | Set 2Below are some more useful functions provided in Python for arrays: Array Typecode FunctionThis function returns the data type by which the array is initialized. In this example, we are using arr.typecode to find out the data
3 min read
Operator Functions in Python | Set 2
Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particul
5 min read
How to pass an array to a function in Python
In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is
4 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements whi
2 min read
Pass a List to a Function in Python
In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways.Passing list by Reference When we pass a list to a function by reference, it refers to the original list. If we make any
2 min read
set() Function in python
set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an i
3 min read
Python Set discard() Function
Python discard() is a built-in method to remove elements from the set. The discard() method takes exactly one argument. This method does not return any value. Example: In this example, we are removing the integer 3 from the set with discard() in Python. Python3 my_set = {1, 2, 3, 4, 5} my_set.discar
3 min read
set() Constructor in Python
In Python, the set() constructor is used to create a set object. A set is a built-in data type that stores an unordered collection of unique elements. The set() constructor can be used to create an empty set or convert other data types (like lists, tuples, or strings) into a set.Example:Python# Exam
2 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on th
3 min read