Python Arrays 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. a = [1, "Hello", [3.14, "world"]] a.append(2) # Add an integer to the end print(a) Output [1, 'Hello', [3.14, 'world'], 2] Note: Python does 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 the NumPy 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. 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. import numpy as np a = np.array([1, 2, 3, 4]) # Element - wise operations print(a * 2) # Multi - dimensional array res = np.array([[1, 2], [3, 4]]) print(res * 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. Unlike Python lists (can store elements of mixed types), arrays must have all elements of same type. Having only homogeneous elements makes it memory - efficient. import array as arr a = arr.array('i', [1, 2, 3]) # accessing First Araay print(a[0]) # adding element to array a.append(5) print(a) Output 1 array('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. import array as arr a = arr.array('i', [1, 2, 3]) for i in range(0, 3): print(a[i], end=" ") Output 1 2 3 Python Array Index Adding Elements to an Array Elements can be added to the Python Array by using built - in insert() 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. import array as arr a = arr.array('i', [1, 2, 3]) print(*a) a.insert(1, 4) # Insert 4 at index 1 print(*a) Output 1 2 3 1 4 2 3 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. import array as arr a = 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]) Output 1 4 3.2 3.3 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. import array a = array.array('i', [1, 2, 3, 1, 5]) # remove first occurance of 1 a.remove(1) print(a) # remove item at index 2 a.pop(2) print(a) Output array('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 Python Index Slicing • 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]. import array as arr a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = arr.array('i', a) res = a[3:8] print(res) res = a[5:] print(res) res = a[:] print(res) Output [4, 5, 6, 7, 8] [6, 7, 8, 9, 10] [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. import array a = array.array('i', [1, 2, 3, 1, 2, 5]) # index of 1st occurrence of 2 print(a.index(2)) # index of 1st occurrence of 1 print(a.index(1)) Output 1 0 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. import array a = array.array('i', [1, 2, 3, 1, 2, 5]) # update item at index 2 a[2] = 6 print(a) # update item at index 4 a[4] = 8 print(a) Output array('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 use count() method to count given item in array. import array a = array.array('i', [1, 2, 3, 4, 2, 5, 2]) count = a.count(2) print(count) Output 3 Reversing Elements in an Array In order to reverse elements of an array we need to simply use reverse method. import array a = array.array('i', [1, 2, 3, 4, 5]) a.reverse() print(*a) Output 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 a. import array as arr a = arr.array('i', [1, 2, 3,4,5]) a.extend([6,7,8,9,10]) print(a) Output array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Find Common Elements in Two Arrays in Python Given two arrays arr1[] and arr2[] , the task is to find all the common elements among them. Examples : Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {3, 4, 5, 6, 7} Output: 3 4 5 Explanation : 3, 4 and 5 are common to both the arrays. Input: arr1: {2, 4, 0, 5, 8}, arr2: {0, 1, 2, 3, 4} Output: 0 2 4 Explanation : 0, 2 and 4 are common to both the arrays. Find Common Elements in Two Arrays using Brute Force: This is a brute force approach, simply traverse in the first array, for every element of the first array traverse in the second array to find whether it exists there or not, if true then check it in the result array (to avoid repetition), after that if we found that this element is not present in result array then print it and store it in the result array. Step - by - step approach: • Iterate over each element in arr1 • For each element in arr1 , iterate over each element in arr2 • Compare the current element of arr1 with each element of arr2 • If a common element is found between the two arrays, proceed to the next steps. Otherwise, continue to the next iteration. • Check if the common element found is already present in the result array. • If the common element is not a duplicate , add it to the result array. • Print the common elements found during the iterations. Below is the implementation of the above approach: # Python Program for find commom element using two array import array arr1 = array.array('i', [1, 2, 3, 4, 5]) arr2 = array.array('i', [3, 4, 5, 6, 7]) result = array.array('i') print("Common elements are:", end=" ") # To traverse array1. for i in range(len(arr1)): # To traverse array2. for j in range(len(arr2)): # To match elements of array1 with elements of array2. if arr1[i] == arr2[j]: # Check whether the found element is already present in the result array or not. if arr1[i] not in result: result.append(arr1[i]) print(arr1[i], end=" ") break Output Common elements are: 3 4 5 Find Common Elements in Two Arrays Using List Comprehension: To find the common elements in two arrays in python, we have used list comprehension. For each element X in arr1 , we check if X is present in arr2 and store it in a list Step - by - step approach: • Use list comprehension to iterate over each element x in arr1 o For each element, check if it exists in arr2 . If it does, add it to a new array called common_elements. • Convert the common_elements array to a list and return it. • Print the result. Below is the implementation of the above approach: # Python Program for the above approach from array import array def find_common_elements(arr1, arr2): common_elements = array('i', [x for x in arr1 if x in arr2]) return list(common_elements) arr1 = array('i', [1, 2, 3, 4, 5]) arr2 = array('i', [3, 4, 5, 6, 7]) common_elements = find_common_elements(arr1, arr2) print("Common elements:", common_elements) Output Common elements: [3, 4, 5] Find Common Elements in Two Arrays using Sorting : To find the common elements in two arrays in Python, we have to first sort the arrays, then just iterate in the sorted arrays to find the common elements between those arrays. Step - by - step approach: • Sort both arrays arr1 and arr2 in non - decreasing order. • Initialize two pointers pointer1 and pointer2 to the beginning of both arrays. • Iterate through both arrays simultaneously: o If the elements pointed by pointer1 and pointer2 are equal, add the element to the result vector and move both pointers forward. o If the element in arr1 pointed by pointer1 is less than the element in arr2 pointed by pointer2 , move pointer1 forward. o If the element in arr2 pointed by pointer2 is less than the element in arr1 pointed by pointer1 , move pointer2 forward. • Repeat this process until one of the pointers reaches the end of its array. • Return the result containing the common elements found in both arrays. Below is the implementation of the above approach: import array def find_common_ elements(arr1, arr2): # Convert arrays to lists for sorting arr1_list = list(arr1) arr2_list = list(arr2) # Sort both lists in non - decreasing order arr1_list.sort() arr2_list.sort() # Initialize pointers pointer1 = 0 pointer2 = 0 # Initialize an empty array to store common elements common_elements = array.array('i') # Iterate through both arrays simultaneously while pointer1 < len(arr1_list) and pointer2 < len(arr2_list): # If the elements pointed by pointer1 and pointer2 are equal if arr1_list[pointer1] == arr2_list[pointer2]: # Add the element to the result array common_elements.append(arr1_list[pointer1]) # Move both pointers forward pointer1 += 1 pointer2 += 1 # If the element in arr1 pointed by pointer1 is less than the element in arr2 pointed by pointer2 elif arr1_list[pointer1] < arr2_list[pointer2]: # Move pointer1 forward pointer1 += 1 # If the element in arr2 pointed by pointer2 is less than the element in arr1 pointed by pointer1 else: # Move pointer2 forward pointer2 += 1 return common_elements # Test the function with example arrays arr1 = array.array('i', [1, 2, 3, 4, 5]) arr2 = array.array('i', [3, 4, 5, 6, 7]) common_elements = find_common_elements(arr1, arr2) print "Common elements:", for element in common_elements: print element, Output Common elements: 3 4 5 Find Common Elements in Two Arrays Using Sets: To find the common elements in two arrays in Python, in this approach we will use sets. Initially, we convert both the arrays arr1 and arr2 to sets set1 and set2 . Then, we use the intersection method of set to find the common elements in both the sets. Finally, we return the common elements as a list Step - by - step approach: • Import the array module to use arrays in Python. • Define a function named find_common_elements that takes two arrays ( arr1 and arr2 ) as input. • Within the function, convert both arrays to sets ( set1 and set2 ) for faster lookup. • Find the intersection of the sets ( set1.intersection(set2)) , which represents the common elements between the two arrays. • Convert the set of common elements to a list and return it. • Initialize two arrays arr1 and arr2 . Call the find_common_elements function with these arrays and store the result in common_elements • Print the result Below is the implementation of the above approach: # Python Program for the above approach from array import array def find_common_elements(arr1, arr2): # Convert arrays to sets for faster lookup set1 = set(arr1) set2 = set(arr2) # Find intersection of the sets (common elements) common_elements = set1.intersection(set2) return list(common_elements) arr1 = array('i', [1, 2, 3, 4, 5]) arr2 = array('i', [3, 4, 5, 6, 7]) common_elements = find_common_elements(arr1, arr2) print("Common elements:", common_elements) Output Common elements: [3, 4, 5] Find Common Elements in Two Arrays Using Hash Maps In this approach, we can utilize hash maps to efficiently find the common elements between the two arrays. We'll create a hash map to the store the frequency of the each element in the first array and then iterate through the second array to the check if e ach element exists in the hash map. If an element exists in the hash map and its frequency is greater than 0 and we'll add it to the list of common elements and decrease its frequency in the hash map. Here's the step - by - step algorithm: • Create a hash map to store the frequency of the each element in the first array where the key is the element and the value is its frequency. • Iterate through the second array. • For each element in the second array and check if it exists in the hash map and its frequency is greater than 0. • If both conditions are met add the element to the list of the common elements and decrease its frequency in the hash map. • After iterating through the second array, return the list of the common elements. Example code: def GFG(arr1, arr2): # Create a hash map to store the frequency of the each element in arr1 frequency_map = {} for num in arr1: frequency_map[num] = frequency_map.get(num, 0) + 1 # Initialize a list to store the common elements common_elements = [] # Iterate through arr2 to the find common elements for num in arr2: if num in frequency_map and frequency_map[num] > 0: common_elements.append(num) frequency_map[num] - = 1 return common_elements # Test the function with the example arrays arr1 = [1, 2, 3, 4, 5] arr2 = [3, 4, 5, 6, 7] common_elements = GFG(arr1, arr2) print("Common elements:", common_elements) output : Common elements: 3, 4, 5 How to pass an array to a function in Python Arrays in Python are implemented using the array module , which allows you to store elements of a specific type. You can pass an entire array to a function to perform various operations. Syntax to create an array array(data_type, value_list) In this article, we'll explore how to pass arrays and lists to functions, with practical examples for both. Example 1: Iterate Over an Array We need to import an array, and after that, we will create an array with its datatype and elements, and then we will pass it to the function to iterate the elements in a list. from array import * def show(arr): for i in arr: print(i, end=', ') arr = array('i', [16, 27, 77, 71, 70, 75, 48, 19, 110]) show(arr) Output 16, 27, 77, 71, 70, 75, 48, 19, 110, Explanation: show() function receives an array and iterates over it using a for loop to print each element. Example 2: Multiply All Elements of an Array We need to import an array, and after that, we will create an array and pass it to a function to multiply the elements in a list. from array import * def Product(arr): p = 1 for i in arr: p *= i print("Product: ", p) arr = array('f', [4.1, 5.2, 6.3]) Product(arr) Output Product: 134.31599601554856 Passing a List to a Function The passing of parameters is not restricted to data types. This implies that variables of various data types can be passed in this procedure. So for instance, if we have thousands of values stored in a list and we want to manipulate those values in a specific function, we need to pass an entire list to the specific function. Syntax to create a list: var_name = [ele1, ele2, ...] Let’s explore how to pass lists to functions in Python: Example 1: Print All Elements of a List def print_animals(animals): for a in animals: print(a) ani = ["Cat", "Dog", "Tiger", "Giraffe", "Wolf"] print_animals(ani) Output Cat Dog Tiger Giraffe Wolf Explanation: print_animals() function takes a list animals and prints each animal using a for loop. Example 2: Find the Product of All Numbers in a List In a similar fashion let us perform another program where the list will be of type integers and we will be finding out the product of all the numbers present in the list. def Product(nums): p = 1 for i in nums: p *= i print("Product: ", p) l = [4, 5, 6] Product(l) Output Product: 120 Example 3: Using *args to Pass a Variable Number of Arguments Sometimes, the number of elements in a list isn’t fixed beforehand. In such cases, you can use *args to pass a variable number of arguments to a function. def Prod(*arguments): p = 1 for i in arguments: p *= i print("Product: ", p) Prod(4, 5, 1, 2) Output Product: 40 How to Create String Array in Python ? To create a string array in Python, different methods can be used based on the requirement. A list can store multiple strings easily, NumPy arrays offer more features for large - scale data and the array module provides type - restricted storage. Each method helps in managing collections of text values effectively. Using List The simplest and easiest way to create any type of array in Python is by using List data structure. It is the most widely used method to create an array. There are various ways to create array using list. Direct Initialization In this method, when a list array is created, the values are assigned during the declaration. Later on an element can be added or removed from this array. arr = ["Geeks", "for", "Geeks"] print(arr[1]) Output for Using Numpy Arrays Numpy module in Python is used for working with array. Using the numpy module's array() function, a string array can be created easily. import numpy as np arr = np.array(["Geeks","for","Geeks"]) print(arr) print(arr[2]) Output ['Geeks' 'for' 'Geeks'] Geeks Using Array Module Python array module is specifically used to create and manipulate arrays in Python. Although the array module does not support string datatype, but it can be modified to store the Unicode characters as strings. from array import array arr = array('u', "GeeksforGeeks") print(arr[4]) Output s Task 01 : Write a program that declares an array of 5 integer elements, initializes them one by one and displays them. Output: Array elements are: 10 20 30 40 50 Task 0 2 : Write a program that declares an array of 5 elements, initializes them one by one and displays only the 2 nd and 4 th elements of an array.