Python From Beginner to Advanced

0% completed

Previous
Next
Python - Array Methods

Array methods in Python are integral for manipulating collections of homogeneous data. These methods allow for various operations such as adding elements, clearing the array, making copies, and more, making arrays highly versatile for data manipulation tasks. Properly utilizing these methods can significantly enhance data handling and processing efficiency in Python applications.

Array Methods

Here's a summary of some common array methods, each rephrased to ensure clarity:

MethodDescriptionTime Complexity
append()Appends a new item to the end of the array, increasing its size by one.O(1)
clear()Eliminates all items from the array, resulting in an empty array.O(1)
copy()Creates and returns a new array that contains the same items as the original.O(n)
count()Counts and returns the frequency of a specified item in the array.O(n)
extend()Adds multiple items from another iterable (like a list) to the end of the array.O(k)
index()Finds and returns the position of the first occurrence of a specified item.O(n)
insert()Inserts an item at a designated position within the array.O(n)
pop()Removes the item at a given position in the array, or the last item if no index is provided.O(1) for last item, O(n) for other positions
remove()Deletes the first occurrence of a specified item from the array.O(n)
reverse()Reverses the order of items in the array, in place.O(n)
sorted()Orders the items of the array in ascending or a custom order.O(n \log n)

Example 1: Adding and Removing Elements

This example demonstrates how to add elements to the end of an array, remove elements, and reverse the array order.

Python3
Python3

. . . .

Explanation:

  • numbers.append(4): Adds 4 to the end of the numbers array.
  • numbers.pop(): Removes the last item from the array (4) and returns it.
  • numbers.reverse(): Reverses the order of the array elements in place.

Example 2: Extending and Sorting Arrays

This example shows how to extend an array with elements from another iterable and sort the array.

Python3
Python3

. . . .

Explanation:

  • Extend the array: The extend() method adds more elements [5, 4, 6] to the numbers array.
  • Sort the Aray: The sorted() method is used to sort the elements of the array, resulting in [1, 2, 3, 4, 5, 6].
  • Convert back to array (if needed): If you need to keep the sorted data as an array, it is converted back using arr.array('i', sorted_numbers).

These examples illustrate how to use various array methods to manipulate data within arrays effectively. By understanding these methods, you can perform a wide range of operations that are fundamental to data processing and manipulation in Python.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next