Category: Arrays

  • Array Exercises

    Example 1

    Python program to find the largest number in an array −

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])print(a)
    largest = a[0]for i inrange(1,len(a)):if a[i]>largest:
    
      largest=a[i]print("Largest number:", largest)</pre>

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Largest number: 20
    Example 2
    Python program to store all even numbers from an array in another array −

    import array as arr
    a = arr.array('i', [10,5,15,4,6,20,9])
    print (a)
    b = arr.array('i')
    for i in range(len(a)):
    if a[i]%2 == 0:
    b.append(a[i])
    print ("Even numbers:", b)
    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Even numbers: array('i', [10, 4, 6, 20])
    Example 3
    Python program to find the average of all numbers in a Python array −

    import array as arr
    a = arr.array('i', [10,5,15,4,6,20,9])
    print (a)
    s = 0
    for i in range(len(a)):
    s+=a[i]
    avg = s/len(a)
    print ("Average:", avg)

    # Using sum() function
    avg = sum(a)/len(a)
    print ("Average:", avg)
    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Average: 9.857142857142858
    Average: 9.857142857142858
    Exercise Programs
    Python program find difference between each number in the array and the average of all numbers

    Python program to convert a string in an array

    Python program to split an array in two and store even numbers in one array and odd numbers in the other.

    Python program to perform insertion sort on an array.

    Python program to store the Unicode value of each character in the given array.
  • Array Methods

    The array module in Python offers an efficient object type for representing arrays of basic values like characters, integers, and floating point numbers. Arrays are similar to lists but it stores a collection of homogeneous data elements in order. At the time of creating array’s type is specified using a single character type code.

    Array methods provides various operations on array objects, including appending, extending, and manipulating elements. These methods are used for efficient handling of homogeneous collections of basic data types, making them suitable for tasks requiring compact data storage, such as numerical computations.

    Python Array Class

    The array class defines several methods, including adding and removing elements, obtaining information about the array, manipulating array elements, and converting arrays to and from other data types. Below are categorized methods based on their functionality. Let’s explore and understand the functionality of each method.

    Arrays are created using the array.array(typecode[, initializer]) class, where typecode is a single character that defines the type of elements in the array, and initializer is an optional value used to initialize the array.

    Adding and Removing Elements

    Below methods are used for appending, extending, inserting, and removing elements from arrays −

    Sr.No.Methods with Description
    1append(x)Appends a new item with value x to the end of the array.
    2extend(iterable)Appends items from iterable to the end of the array.
    3insert(i, x)Inserts a new item with value x before position i.
    4pop([i])Removes and returns the item with index i. If i is not specified, removes and returns the last item.
    5remove(x)Removes the first occurrence of x from the array.

    Information and Utility Methods

    These methods are used for obtaining information about arrays and to perform utility operations −

    Sr.No.Methods with Description
    1buffer_info()Returns a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold the arrays contents.
    2count(x)Returns the number of occurrences of x in the array.
    3index(x[, start[, stop]])Returns the smallest index where x is found in the array. Optional start and stop arguments can specify a sub-range to search.

    Manipulating Array Elements

    Following methods are used for manipulating array elements, such as reversing the array or byteswapping values.

    Sr.No.Methods with Description
    1reverse()Reverses the order of the items in the array.
    2byteswap()“Byteswaps” all items of the array, useful for reading data from a file written on a machine with a different byte order.

    Conversion Methods

    These methods are used to convert arrays to and from bytes, files, lists, and Unicode strings.

    Sr.No.Methods with Description
    1frombytes(buffer)Appends items from the bytes-like object, interpreting its content as an array of machine values.
    2tobytes()Converts the array to a bytes representation.
    3fromfile(f, n)Reads n items from the file object f and appends them to the array.
    4tofile(f)Writes all items to the file object f.
    5fromlist(list)Appends items from the list to the array.
    6tolist()Converts the array to a list with the same items.
    7fromunicode(s)Extends the array with data from the given Unicode string. The array must have type code ‘u’.
    8tounicode()Converts the array to a Unicode string. The array must have type code ‘u’.
  • Join Arrays

    The process of joining two arrays is termed as Merging or concatenating. Python provides multiple ways to merge two arrays such as append() and extend() methods. But, before merging two arrays always ensure that both arrays are of the same data type otherwise program will throw error.

    In Pythonarray is a homogenous collection of Python’s built in data types such as strings, integer or float objects. However, array itself is not a built-in type, instead we need to use the Python’s built-in array module.

    Merge Python Array

    Join two Arrays in Python

    To join arrays in Python, use the following approaches −

    • Using append() method
    • Using + operator
    • Using extend() method

    Using append() Method

    To join two arrays, we can append each item from one array to other using append() method. To perform this operation, run a for loop on the original array, fetch each element and append it to a new array.

    Example: Join Two Arrays by Appending Elements

    Here, we use the append() method to join two arrays.

    import array as arr
    
    # creating two arrays
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i',[2,7,8,11,3,10])# merging both arraysfor i inrange(len(b)):
       a.append(b[i])print(a)

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 3, 10])
    

    Using + operator

    We can also use + operator to concatenate or merge two arrays. In this approach, we first convert arrays to list objects, then concatenate the lists using the + operator and convert back to get merged array.

    Example: Join Two Arrays by Converting to List Objects

    In this example, we will see how to join two arrays using + operator.

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i',[2,7,8,11,3,10])
    x = a.tolist()
    y = b.tolist()
    z = x+y
    a = arr.array('i', z)print(a)

    The above code will display the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 3, 10])
    

    Using extend() Method

    Another approach to concatenate arrays is the use of extend() method from the List class. Similar to above approach, we first convert the array to a list and then call the extend() method to merge the two lists.

    Example: Join Two Arrays using extend() Method

    In the following example, we will use the extend() method to concatenate two arrays in Python.

    import array as arr
    a = arr.array('i',[88,99,77,66,44,22])
    b = arr.array('i',[12,17,18,11,13,10])
    a.extend(b)print(a)

    It will produce the following output −

    array('i', [88, 99, 77, 66, 44, 22, 12, 17, 18, 11, 13, 10])
    
  • Sort Arrays

    Python’s array module defines the array class. An object of array class is similar to the array as present in Java or C/C++. Unlike the built-in Python sequences, array is a homogenous collection of either strings, or integers, or float objects.

    The array class doesn’t have any function/method to give a sorted arrangement of its elements. However, we can achieve it with one of the following approaches −

    • Using a sorting algorithm
    • Using the sort() method from List
    • Using the built-in sorted() function

    Let’s discuss each of these methods in detail.

    Python Array Sorting

    Sort Arrays Using a Sorting Algorithm

    We implement the classical bubble sort algorithm to obtain the sorted array. To do it, we use two nested loops and swap the elements for rearranging in sorted order.

    Example

    Run the following code using a Python code editor −

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])for i inrange(0,len(a)):for j inrange(i+1,len(a)):if(a[i]> a[j]):
    
         temp = a[i];
         a[i]= a[j];
         a[j]= temp;print(a)</pre>

    It will produce the following output −

    array('i', [4, 5, 6, 9, 10, 15, 20])
    Sort Arrays Using sort() Method of List
    Even though array module doesn't have a sort() method, Python's built-in List class does have a sort method. We shall use it in the next example.

    First, declare an array and obtain a list object from it, using tolist() method. Then, use the sort() method to get a sorted list. Lastly, create another array using the sorted list which will display a sorted array.

    Example
    The following code shows how to get sorted array using the sort() method.

    import array as arr

    # creating array
    orgnlArray = arr.array('i', [10,5,15,4,6,20,9])
    print("Original array:", orgnlArray)
    # converting to list
    sortedList = orgnlArray.tolist()
    # sorting the list
    sortedList.sort()

    # creating array from sorted list
    sortedArray = arr.array('i', sortedList)
    print("Array after sorting:",sortedArray)
    The above code will display the following output −

    Original array: array('i', [10, 5, 15, 4, 6, 20, 9])
    Array after sorting: array('i', [4, 5, 6, 9, 10, 15, 20])
    Sort Arrays Using sorted() Method
    The third technique to sort an array is with the sorted() function, which is a built-in function.

    The syntax of sorted() function is as follows −

    sorted(iterable, reverse=False)
    The function returns a new list containing all items from the iterable in ascending order. Set reverse parameter to True to get a descending order of items.

    The sorted() function can be used along with any iterable. Python array is an iterable as it is an indexed collection. Hence, an array can be used as a parameter to sorted() function.

    Example
    In this example, we will see the use of sorted() method in sorting an array.

    import array as arr
    a = arr.array('i', [4, 5, 6, 9, 10, 15, 20])
    sorted(a)
    print(a)
    It will produce the following output −

    array('i', [4, 5, 6, 9, 10, 15, 20])

  • Reverse Arrays

    Reversing an array is the operation of rearranging the array elements in the opposite order. There are various methods and approaches to reverse an array in Python including reverse() and reversed() methods.

    In Python, array is not one of the built-in data types. However, Python’s standard library has array module which helps us to create a homogenous collection of string, integer or float types.

    Reverse Array Operation Python

    Ways to Reverse an Array in Python

    To reverse an array, use the following approaches −

    • Using slicing operation
    • Using reverse() method
    • Using reversed() method
    • Using for loop

    Using slicing operation

    Slicing operation is the process of extracting a part of array within the specified indices. In Python, if we use the slice operation in the form [::-1] then, it will display a new array by reversing the original one.

    In this process, the interpreter starts from the end and stepping backwards by 1 until it reaches the beginning of the array. As a result, we get a reverse copy of original array.

    Example

    The below example demonstrates how to use the slicing operation to reverse an array in Python.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[88,99,77,55,66])print("Original array:", numericArray)
    revArray = numericArray[::-1]print("Reversed array:",revArray)

    When you run the code, it will produce the following output −

    Original array: array('i', [88, 99, 77, 55, 66])
    Reversed array: array('i', [66, 55, 77, 99, 88])
    

    Reverse an Array Using reverse() Method

    We can also reverse the sequence of numbers in an array using the reverse() method of list class. Here, list is a built-in type in Python.

    Since reverse() is a method of list class, we cannot directly use it to reverse an array created through the Python array module. We have to first transfer the contents of an array to a list with tolist() method of array class, then we call the reverse() method and at the end, when we convert the list back to an array, we get the array with reversed order.

    Example

    Here, we will see the use of reverse() method in reversing an array in Python.

    import array as arr
    
    # creating an array
    numericArray = arr.array('i',[10,5,15,4,6,20,9])print("Array before reversing:", numericArray)# converting the array into list
    newArray = numericArray.tolist()# reversing the list
    newArray.reverse()# creating a new array from reversed list
    revArray = arr.array('i', newArray)print("Array after reversing:",revArray)

    It will produce the following output −

    Array before reversing: array('i', [10, 5, 15, 4, 6, 20, 9])
    Array after reversing: array('i', [9, 20, 6, 4, 15, 5, 10])
    

    Reverse an Array Using reversed() Method

    The reversed() method is another way to reverse elements of an array. It accepts an array as a parameter value and returns an iterator object that dispalys array elements in reverse order.

    Example

    In this example, we are using the reversed() method to reverse an array in Python.

    import array as arr
    
    # creating an array
    numericArray = arr.array('i',[12,10,14,16,20,18])print("Array before reversing:", numericArray)# reversing the array
    newArray =list(reversed(numericArray))# creating a new array from reversed list
    revArray = arr.array('i', newArray)print("Array after reversing:",revArray)

    On executing the above code, it will display the following output −

    Array before reversing: array('i', [12, 10, 14, 16, 20, 18])
    Array after reversing: array('i', [18, 20, 16, 14, 10, 12])
    

    Using for Loop

    To reverse an array using a for loop, we first traverse the elements of the original array in reverse order and then append each element to a new array.

    Example

    The following example shows how to reverse an array in Python using for loop.

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i')for i inrange(len(a)-1,-1,-1):
       b.append(a[i])print(a)print(b)

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    array('i', [9, 20, 6, 4, 15, 5, 10])
  • Copy Arrays

    In Python, copying an array refers to the process of creating a new array that contains all the elements of the original array. This operation can be done using assignment operator (=) and deepcopy() method. In this chapter, we discuss how to copy an array object to another. But, before getting into the details let’s breifly discuss arrays.

    Python’s built-in sequence types i.e. listtuple, and string are indexed collection of items. However, unlike arrays in C/C++, Java etc. they are not homogenous, in the sense the elements in these types of collection may be of different types. Python’s array module helps you to create object similar to Java like arrays.

    Python arrays can be of string, integer or float type. The array class constructor is used as follows −

    import array
    obj = array.array(typecode[, initializer])

    Where, the typecode may be a character constant representing the data type.

    Copy Arrays Using Assignment Operator

    We can assign an array to another by using the assignment operator (=). However, such assignment doesn’t create a new array in the memory. Instead, it creates a new reference to the same array.

    Example

    In the following example, we are using assignment operator to copy array in Python.

    import array as arr
    a = arr.array('i',[110,220,330,440,550])
    b = a
    print("Copied array:",b)print(id(a),id(b))

    It will produce the following output −

    Copied array: array('i', [110, 220, 330, 440, 550])
    134485392383792 134485392383792
    

    Check the id() of both a and b. Same value of id confirms that simple assignment doesn’t create a copy. Since “a” and “b” refer to the same array object, any change in the array “a” will reflect in “b” too −

    a[2]=10print(a,b)

    It will produce the following output −

    array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 10, 440, 550])

    Copy Arrays Using Deep Copy

    To create another physical copy of an array, we use another module in Python library, named copy and use deepcopy() function in the module. A deep copy constructs a new compound object and then, recursively inserts copies into it of the objects found in the original.

    Example

    The following example demonstrates how to copy array in Python −

    import array as arr
    import copy
    a = arr.array('i',[110,220,330,440,550])
    b = copy.deepcopy(a)print("Copied array:",b)

    On executing, it will produce the following output −

    Copied array: array('i', [110, 220, 330, 440, 550])
    

    Now check the id() of both “a” and “b”. You will find the ids are different.

    print(id(a),id(b))

    It will produce the following output −

    2771967069936 2771967068976
    

    This proves that a new object “b” is created which is an actual copy of “a”. If we change an element in “a”, it is not reflected in “b”.

    a[2]=10print(a,b)

    It will produce the following output −

    array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 330, 440, 550])
  • Loop Arrays

    Loops are used to repeatedly execute a block of code. In Python, there are two types of loops named for loop and while loop. Since the array object behaves like a sequence, you can iterate through its elements with the help of loops.

    The reason for looping through arrays is to perform operations such as accessing, modifying, searching, or aggregating elements of the array.

    Python for Loop with Array

    The for loop is used when the number of iterations is known. If we use it with an iterable like array, the iteration continues until it has iterated over every element in the array.

    Example

    The below example demonstrates how to iterate over an array using the “for” loop −

    import array as arr
    newArray = arr.array('i',[56,42,23,85,45])for iterate in newArray:print(iterate)

    The above code will produce the following result −

    56
    42
    23
    85
    45

    Python while Loop with Array

    In while loop, the iteration continues as long as the specified condition is true. When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update the loop variable.

    Example

    The following example shows how you can loop through an array using a while loop −

    import array as arr
    
    # creating array
    a = arr.array('i',[96,26,56,76,46])# checking the length
    l =len(a)# loop variable
    idx =0# while loopwhile idx < l:print(a[idx])# incrementing the while loop
       idx+=1

    On executing the above code, it will display the following output −

    96
    26
    56
    76
    46
    

    Python for Loop with Array Index

    We can find the length of array with built-in len() function. Use it to create a range object to get the series of indices and then access the array elements in a for loop.

    Example

    The code below illustrates how to use for loop with array index.

    import array as arr
    a = arr.array('d',[56,42,23,85,45])
    l =len(a)for x inrange(l):print(a[x])

    On running the above code, it will show the below output −

    56.0
    42.0
    23.0
    85.0
    45.0
  • Remove Array Items

    Removing array items in Python

    Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

    The array module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

    Python does not provide built-in support for arrays, however, we can use the array module to achieve the functionality like an array.

    Remove First Occurrence

    To remove the first occurrence of a given value from the array, use remove() method. This method accepts an element and removes it if the element is available in the array.

    Syntax

    array.remove(v)

    Where, v is the value to be removed from the array.

    Example

    The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.remove(311)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 411, 511])
    

    Remove Items from Specific Indices

    To remove an array element from specific index, use the pop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

    Syntax

    array.pop(i)

    Where, i is the index for the element to be removed.

    Example

    In this example, we will see how to use pop() method to remove elements from an array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.pop(3)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 311, 511])
  • Add Array Items

    Python array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.

    Python does not have built-in support for arrays, it uses array module to achieve the functionality like an array.

    Adding Elements to Python Array

    There are multiple ways to add elements to an array in Python −

    • Using append() method
    • Using insert() method
    • Using extend() method

    Using append() method

    To add a new element to an array, use the append() method. It accepts a single item as an argument and append it at the end of given array.

    Syntax

    Syntax of the append() method is as follows −

    append(v)

    Where,

    • v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

    Example

    Here, we are adding element at the end of specified array using append() method.

    import array as arr
    a = arr.array('i',[1,2,3])
    a.append(10)print(a)

    It will produce the following output −

    array('i', [1, 2, 3, 10])
    

    Using insert() method

    It is possible to add a new element at the specified index using the insert() method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.

    Syntax

    Syntax of this method is shown below −

    insert(i, v)

    Where,

    • i − The index at which new value is to be inserted.
    • v − The value to be inserted. Must be of the arraytype.

    Example

    The following example shows how to add array elements at specific index with the help of insert() method.

    import array as arr
    a = arr.array('i',[1,2,3])
    a.insert(1,20)print(a)

    It will produce the following output −

    array('i', [1, 20, 2, 3])
    

    Using extend() method

    The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.

    Syntax

    This method has the following syntax −

    extend(x)

    Where,

    • x − This parameter specifies an array or iterable.

    Example

    In this example, we are adding items from another array to the specified array.

    import array as arr
    a = arr.array('i',[1,2,3,4,5])
    b = arr.array('i',[6,7,8,9,10])
    a.extend(b)print(a)

    On executing the above code, it will produce the following output −

    array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    
  • Access Array Items

    Accessing an array items in Python refers to the process of retrieving the value stored at a specific index in the given array. Here, index is an numerical value that indicates the location of array items. Thus, you can use this index to access elements of an array in Python.

    An array is a container that holds a fix number of items of the same type. Python uses array module to achieve the functionality like an array.

    Accessing array items in Python

    You can use the following ways to access array items in Python −

    • Using indexing
    • Using iteration
    • Using enumerate() function

    Using indexing

    The process of accessing elements of an array through the index is known as Indexing. In this process, we simply need to pass the index number inside the index operator []. The index of an array in Python starts with 0 which means you can find its first element at index 0 and the last at one less than the length of given array.

    Example

    The following example shows how to access elements of an array using indexing.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])#indexingprint(numericArray[0])print(numericArray[1])print(numericArray[2])

    When you run the above code, it will show the following output −

    111
    211
    311
    

    Using iteration

    In this approach, a block of code is executed repeatedely using loops such as for and while. It is used when you want to access array elements one by one.

    Example

    In the below code, we use the for loop to access all the elements of the specified array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# iteration through for loopfor item in numericArray:print(item)

    On executing the above code, it will display the following result −

    111
    211
    311
    411
    511
    

    Using enumerate() function

    The enumerate() function can be used to access elements of an array. It accepts an array and an optional starting index as parameter values and returns the array items by iterating.

    Example

    In the below example, we will see how to use the enumerate() function to access array items.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# use of enumerate() functionfor loc, val inenumerate(numericArray):print(f"Index: {loc}, value: {val}")

    It will produce the following output −

    Index: 0, value: 111
    Index: 1, value: 211
    Index: 2, value: 311
    Index: 3, value: 411
    Index: 4, value: 511
    

    Accessing a range of array items in Python

    In Python, to access a range of array items, you can use the slicing operation which is performed using index operator [] and colon (:).

    This operation is implemented using multiple formats, which are listed below −

    • Use the [:index] format to access elements from beginning to desired range.
    • To access array items from end, use [:-index] format.
    • Use the [index:] format to access array items from specific index number till the end.
    • Use the [start index : end index] to slice the array elements within a range. You can also pass an optional argument after end index to determine the increment between each index.

    Example

    The following example demonstrates the slicing operation in Python.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# slicing operationprint(numericArray[2:])print(numericArray[0:3])

    On executing the above code, it will display the following result −

    array('i', [311, 411, 511])
    array('i', [111, 211, 311])