In Python, an array is a collection of similar data types stored in contiguous memory locations. The array module allows you to create and manipulate arrays in Python. The most common way to create an array in Python is to use the array() function from the array module, which takes a sequence of numbers as its argument. For example:
import array arr = array.array('f', [1.0, 2.0, 3.0, 4.0])
This creates an array of float values with the specified values. You can then access and manipulate the elements of the array using their index in the array. For example:
print(arr[0]) # prints 1.0 arr[0] = 5.0 print(arr[0]) # prints 5.0
You can also use the built-in len() function to find the length of the array:
print(len(arr)) # prints 4
Arrays help store and manipulate data that is organized into ordered sequences. You can use them to store lists of numbers, strings, or other types of data.
However, they are limited in that they can only store data of a single type. For more complex data structures, you may want to use other data types, such as lists or dictionaries.
Let’s now learn more about arrays in Python with the help of these 15 common Python array programs.
Also Read: Pattern Programs in Python [Star and Alphabetical Patterns]
15 Most Common Python Array Programs
Also Read: Python Reserved Words List With Definitions and Examples
1. Python program to copy all elements of one array into another array
Here is a simple Python program to copy all elements of one array into another array:
# define a function to copy all elements of one array into another def copy_array(arr1, arr2): # iterate over the elements in the first array for i in range(len(arr1)): # copy the element from the first array to the second arr2[i] = arr1[i] # create two arrays arr1 = [1, 2, 3, 4, 5] arr2 = [0, 0, 0, 0, 0] # copy all elements of the first array into the second copy_array(arr1, arr2) # print the second array print(arr2)
This program defines a function called copy_array(), which takes two arrays as arguments. It uses a for loop to iterate over the elements in the first array and copies each element from the first array to the corresponding index in the second array.
After defining the copy_array() function, the program creates arr1 and arr2 and initializes them with some values. It then calls the copy_array() function to copy all elements of arr1 into arr2. Finally, it prints the second array to verify that the elements were copied successfully.
This program would output the following:
[1, 2, 3, 4, 5]
Please note that there are other ways to copy the elements of one array into another in Python, such as using the copy() method or slicing. You can read more about these methods in the Python documentation.
Also Read: Graph Plotting in Python Using Matplotlib
2. Python program to find the frequency of each element in the array
Here is a simple Python program to find the frequency of each element in the array:
# define a function to find the frequency of each element in the array def find_frequency(arr): # create a dictionary to store the frequency of each element frequency = {} # iterate over the elements in the array for element in arr: # if the element is not in the dictionary, add it with a frequency of 1 if element not in frequency: frequency[element] = 1 # otherwise, increment the frequency of the element else: frequency[element] += 1 # return the frequency dictionary return frequency # create an array arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 1] # find the frequency of each element in the array frequencies = find_frequency(arr) # print the frequency of each element for element, frequency in frequencies.items(): print(f"{element}: {frequency}")
This program defines a function called find_frequency(), which takes an array as an argument. It creates an empty dictionary called frequency to store the frequency of each element in the array.
Then, it uses a for loop to iterate over the elements in the array and count the frequency of each element. It stores the frequency of each element in the frequency dictionary and returns the dictionary when all elements have been counted.
After defining the find_frequency() function, the program creates an array called arr and initializes it with some values. It then calls the find_frequency() function to find the frequency of each element in the array and stores the result in a dictionary called frequencies.
Finally, it uses another for loop to iterate over the elements and frequencies in the frequencies dictionary and prints the frequency of each element.
This program would output the following:
1: 3 2: 2 3: 2 4: 2 5: 1
Please note that there are other ways to find the frequency of each element in an array in Python, such as using the Counter class from the collections module. You can read more about these methods in the Python documentation.
Also Read: Intro to Threading in Python [Understand With Examples]
3. Python program to left rotate the elements of an array
Here is a simple Python program to left-rotate the elements of an array:
# Function to left rotate arr[] of size n by d def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) # Function to left Rotate arr[] of size n by 1 def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i+1] arr[n-1] = temp # utility function to print an array def printArray(arr, size): for i in range(size): print("%d"% arr[i], end=" ") # Driver program to test above functions arr = [1, 2, 3, 4, 5, 6, 7] leftRotate(arr, 2, 7) # Rotate array by 2 printArray(arr, 7)
Here, the function leftRotate(arr, d, n) rotates the array arr of size n by d elements. This is done by repeatedly calling the function leftRotatebyOne(arr, n).
The function leftRotatebyOne(arr, n) rotates the array by one element by moving all the elements to the left by one position and copying the first element to the last position.
For example, if the array arr is [1, 2, 3, 4, 5, 6, 7] and d is 2, the function leftRotate(arr, 2, 7) will first call leftRotatebyOne(arr, 7), which will rotate the array to [2, 3, 4, 5, 6, 7, 1].
Then, it will call leftRotatebyOne(arr, 7) again, which will rotate the array to [3, 4, 5, 6, 7, 1, 2]. The final rotated array will be printed using the printArray(arr, size) function.
Also Read: Understanding How Print Statements in Python Work
4. Python program to print the duplicate elements of an array
Here is a simple Python program to print the duplicate elements of an array:
# Function to print duplicate elements in the array def printDuplicates(arr, n): # Create an empty dictionary freq = {} # Traverse the array and store the frequency of each element in the dictionary for i in range(n): if arr[i] in freq: freq[arr[i]] += 1 else: freq[arr[i]] = 1 # Traverse the dictionary and print all the elements with frequency greater than 1 for key, value in freq.items(): if value > 1: print(key, end=" ") # Driver program to test above function arr = [1, 2, 3, 1, 3, 6, 6] n = len(arr) printDuplicates(arr, n)
In this program, the printDuplicates(arr, n) function first creates an empty dictionary freq. It then traverses the array arr of size n and stores the frequency of each element in the dictionary.
After the array has been traversed, the function traverses the dictionary and prints all the elements with a frequency greater than 1.
For example, if the array arr is [1, 2, 3, 1, 3, 6, 6], the dictionary will be {1: 2, 2: 1, 3: 2, 6: 2}. The function will print elements 1, 3, and 6 as they have a frequency greater than 1.
Note: This program only works for arrays of size greater than or equal to 1. If the array size is 0, the program will not work correctly.
Also Read: How to Create a Neural Network in Python
5. Python program to print the elements of an array
Here is a simple Python program to print the elements of an array:
# Function to print the elements of an array def printArray(arr, n): for i in range(n): print(arr[i], end=" ") # Driver program to test above function arr = [1, 2, 3, 4, 5] n = len(arr) printArray(arr, n)
In this program, the printArray(arr, n) function takes an array arr and its size n as arguments. It then uses a for loop to traverse the array and print each element.
For example, if the array arr is [1, 2, 3, 4, 5], the function will print the elements 1, 2, 3, 4, and 5 on separate lines.
Note: This program only works for arrays of size greater than or equal to 1. If the array size is 0, the program will not work correctly.
Also Read: Or Operator in Python
6. Python program to print the elements of an array in reverse order
Here is a simple Python program to print the elements of an array in reverse order:
# Function to print the elements of an array in reverse order def printArrayInReverse(arr, n): for i in range(n-1, -1, -1): print(arr[i], end=" ") # Driver program to test above function arr = [1, 2, 3, 4, 5] n = len(arr) printArrayInReverse(arr, n)
In this program, the printArrayInReverse(arr, n) function takes an array arr and its size n as arguments. It then uses a for loop traverse the array in reverse order and prints each element.
For example, if the array arr is [1, 2, 3, 4, 5], the function will print the elements 5, 4, 3, 2, and 1 on separate lines.
Note: This program only works for arrays of size greater than or equal to 1. If the array size is 0, the program will not work correctly.
Also Read: Natural Language Processing in Python: Techniques
7. Python program to print the elements of an array present on an even position
Here is a simple Python program to print the elements of an array present in an even position:
# Function to print the elements of an array present on an even position def printArrayEvenPositions(arr, n): for i in range(0, n, 2): print(arr[i], end=" ") # Driver program to test above function arr = [1, 2, 3, 4, 5] n = len(arr) printArrayEvenPositions(arr, n)
In this program, the printArrayEvenPositions(arr, n) function takes an array arr and its size n as arguments. It then uses a for loop to traverse the array and prints each element present on an even position (index 0, 2, 4, etc.).
For example, if the array arr is [1, 2, 3, 4, 5], the function will print the elements 1 and 3.
Note: This program only works for arrays of size greater than or equal to 1. If the array size is 0, the program will not work correctly.
Also Read: How to Fix Invalid Syntax Error in Python
8. Python program to print the elements of an array present in an odd position
Here is a simple Python program to print the elements of an array present in an odd position:
# Function to print the elements of an array present on an odd position def printArrayOddPositions(arr, n): for i in range(1, n, 2): print(arr[i], end=" ") # Driver program to test above function arr = [1, 2, 3, 4, 5] n = len(arr) printArrayOddPositions(arr, n)
In this program, the printArrayOddPositions(arr, n) function takes an array arr and its size n as arguments. It then uses a for loop to traverse the array and prints each element present on an odd position (index 1, 3, 5, etc.).
For example, if the array arr is [1, 2, 3, 4, 5], the function will print the elements 2 and 4.
Also Read: How to Fix Unexpected EOF While Parsing Error In Python
9. Python program to print the largest element in an array
Here is a simple Python program to print the largest element in an array:
# Function to find the largest element in the array def findLargest(arr, n): max = arr[0] for i in range(1, n): if arr[i] > max: max = arr[i] return max # Driver program to test above function arr = [10, 20, 30, 40, 50] n = len(arr) print("Largest element in the array:", findLargest(arr, n))
In this program, the findLargest(arr, n) function takes an array arr and its size n as arguments. It then initializes the variable max with the first element of the array and uses a for loop to traverse the array. For each element, if it is greater than the current value of max, max is updated with the new value.
Finally, the function returns the value of max, the largest element in the array.
For example, if the array arr is [10, 20, 30, 40, 50], the function will return the value 50 as the largest element in the array.
Also Read: How To Copy List in Python
10. Python program to print the smallest element in an array
Here is a simple Python program to print the smallest element in an array:
# Function to find the smallest element in the array def findSmallest(arr, n): min = arr[0] for i in range(1, n): if arr[i] < min: min = arr[i] return min # Driver program to test above function arr = [10, 20, 30, 40, 50] n = len(arr) print("Smallest element in the array:", findSmallest(arr, n))
In this program, the findsmallest(arr, n) function takes an array arr and its size n as arguments. It then initializes the variable min with the first element of the array and uses a for loop to traverse the array. If each element is smaller than the current min value, the min is updated with the new value.
Finally, the function returns the value of min, the smallest element in the array.
For example, if the array arr is [10, 20, 30, 40, 50], the function will return the value 10 as the smallest element in the array.
Also Read: 10 Best Programming Apps To Learn Python
11. Python program to print the number of elements present in an array
Here is a simple Python program to print the number of elements present in an array:
# Function to print the number of elements in the array def printArrayLength(arr): n = len(arr) print("Number of elements in the array:", n) # Driver program to test above function arr = [10, 20, 30, 40, 50] printArrayLength(arr)
In this program, the printArrayLength(arr) function takes an array arr as an argument. It then uses the len() function to find the array’s length (number of elements) and prints it.
For example, if the array arr is [10, 20, 30, 40, 50], the function will print the message “Number of elements in the array: 5”.
Also Read: Sending Emails Using Python With Image And PDF Attachments
12. Python program to print the sum of all elements in an array
Here is a simple Python program to print the sum of all elements in an array:
# Function to find the sum of all elements in the array def findSum(arr, n): sum = 0 for i in range(n): sum += arr[i] return sum # Driver program to test above function arr = [10, 20, 30, 40, 50] n = len(arr) print("Sum of all elements in the array:", findSum(arr, n))
In this program, the findSum(arr, n) function takes an array arr and its size n as arguments. It then initializes a variable sum to 0 and uses a for loop to traverse the array. For each element, the value is added to the sum.
Finally, the function returns the value of sum, which is the sum of all elements in the array.
For example, if the array arr is [10, 20, 30, 40, 50], the function will return the value 150 as the sum of all elements in the array.
Also Read: How To Make A Digital Clock In Python Using Tkinter
13. Python program to right-rotate the elements of an array
Here is a simple Python program to right-rotate the elements of an array:
# Function to right rotate arr[] of size n by d def rightRotate(arr, d, n): for i in range(d): rightRotatebyOne(arr, n) # Function to right Rotate arr[] of size n by 1 def rightRotatebyOne(arr, n): temp = arr[n-1] for i in range(n-2, -1, -1): arr[i+1] = arr[i] arr[0] = temp # utility function to print an array def printArray(arr, size): for i in range(size): print("%d"% arr[i], end=" ") # Driver program to test above functions arr = [1, 2, 3, 4, 5, 6, 7] rightRotate(arr, 2, 7) # Rotate array by 2 printArray(arr, 7)
Here, the function rightRotate(arr, d, n) rotates the array arr of size n by d elements. This is done by repeatedly calling the function rightRotatebyOne(arr, n). The function rightRotatebyOne(arr, n) rotates the array by one element by moving all the elements to the right by one position and copying the last element to the first.
For example, if the array arr is [1, 2, 3, 4, 5, 6, 7] and d is 2, the function rightRotate(arr, 2, 7) will first call rightRotatebyOne(arr, 7), which will rotate the array to [7, 1, 2, 3, 4, 5, 6]. Then, it will call rightRotatebyOne(arr, 7) again, which will rotate the array to [6, 7, 1, 2, 3, 4, 5]. The final rotated array will be printed using the printArray(arr, size) function.
Also Read: 35 Funny And Best Python Programming Memes
14. Python program to sort the elements of an array in ascending order
Here is a simple Python program to sort the elements of an array in ascending order:
# Function to sort the array in ascending order def sortArrayAscending(arr, n): for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver program to test above function arr = [64, 34, 25, 12, 22, 11, 90] n = len(arr) sortArrayAscending(arr, n) print ("Sorted array is:") for i in range(n): print ("%d" %arr[i])
In this program, the sortArrayAscending(arr, n) function takes an array arr and its size n as arguments. It then uses two nested for loops to traverse the array and sort the elements in ascending order using the bubble sort algorithm.
For example, if the array arr is [64, 34, 25, 12, 22, 11, 90], the function will sort the array in ascending order, and the final sorted array will be [11, 12, 22, 25, 34, 64, 90].
Also Read: How To Use Python For Browser Games Development?
15. Python program to sort the elements of an array in descending order
Here is a simple Python program to sort the elements of an array in descending order:
# Function to sort the array in descending order def sortArrayDescending(arr, n): for i in range(n): for j in range(0, n-i-1): if arr[j] < arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver program to test above function arr = [64, 34, 25, 12, 22, 11, 90] n = len(arr) sortArrayDescending(arr, n) print ("Sorted array is:") for i in range(n): print ("%d" %arr[i])
In this program, the sortArrayDescending(arr, n) function takes an array arr and its size n as arguments. Here we use the bubble sort algorithm, which uses two nested for loops to traverse the array and sort the elements in descending order.
For example, if the array arr is [64, 34, 25, 12, 22, 11, 90], the function will sort the array in descending order, and the final sorted array will be [90, 64, 34, 25, 22, 12, 11].
Also Read: How To Make A Simple Python 3 Calculator Using Functions
Summary
With this, we sum up our list of the 15 most common Python array programs. Study these programs to understand how the array module works in Python. Subscribe to our newsletter to get these articles straight to your inbox.
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!