How to manipulate Arrays in Python

Knowing multiple ways on how to manipulate arrays in Python is an important step towards efficiently writing code. Here are some common ways to manipulate arrays in Python: 

Indexing: Access individual elements of the array by their index, starting from 0. Example:

arr = [1, 2, 3] 
print(arr[1])
# outputs 2
Python

Slicing: Access a sub-section of the array by specifying start and end indices. Example:

arr = [1, 2, 3, 4, 5]
print(arr[1:3]) 
# outputs [2, 3]
Python


Modifying values
: Change individual elements of the array by assigning new values to them using their indices. Example:

arr = [1, 2, 3]
arr[1] = 4
# print(arr) outputs [1, 4, 3]
Python

Appending: Add elements to the end of the array using the append() method. Example:

arr = [1, 2, 3] 
arr.append(4)
print(arr)
# outputs [1, 2, 3, 4]
Python

Inserting: Add elements at specific indices using the insert() method. Example:

arr = [1, 2, 3]
arr.insert(1, 4)
print(arr)
# outputs [1, 4, 2, 3]
Python

Deleting: Remove elements from the array using the remove() method or del keyword. Example:

arr = [1, 2, 3]
arr.remove(2)
print(arr)
# outputs [1, 3]
Python

Concatenating: Combine two arrays into a single array using the + operator. Example:

arr1 = [1, 2]
arr2 = [3, 4]
arr3 = arr1 + arr2
print(arr3)
# outputs [1, 2, 3, 4]
Python

Note that Python has a built-in list data structure which is dynamic array and can be used for these operations.

How to manipulate Arrays in Python
Ways of manipulating arrays in Python

Leave a Reply