arrays in python

arrays in python

Last updated on 10th Oct 2020, Blog, Tutorials

About author

Shalini ((Sr Technical Project Manager ) )

Delegates in Corresponding Technical Domain with 6+ Years of Experience. Also, She is a Technology Writer for Past 3 Years & Share's this Informative Blogs for us.

(5.0) | 12547 Ratings 2029

In programming, an array is a homogenous (belonging to the same data type) collection of elements. Unlike languages like C++, Java, and JavaScript, arrays aren’t among the built-in Python data structures.

Although Python doesn’t have built-in support for arrays, that doesn’t stop programmers from implementing them.

Subscribe For Free Demo

Error: Contact form not found.

What are Python Arrays?

As a replacement to arrays, Python has lists. Nonetheless, Python supports arrays of numeric values using the array module.

When creating arrays using the array module in Python, remember that all elements of the array must be of the same type. If this is not the case then an error will be produced. For instance,

a = [1, 22, 240] is valid

but

a = [1, 22, 240, “Akhil”] is not valid and will thus, yield an error

How does Array Work in Python?

The array is stored in contiguous memory locations, where the index is a sequence of numbers that represents the values stored at every particular index. To access or refer the value at a particular index in an array we make use of a set of square brackets [ ], also we can use the for-in loop to iterate through the array. Array has indices (plural form of an index) and values. At each index, a value is stored. Why we use arrays is because it is difficult to store and remember hundred of numbers at a time, it would be simpler and easier to use arrays in that case, say the integer array is like the following. array (‘i’, [1, 2 , 3, 4 , 5, 6, 7, 8, 9,10] ) then to access these values we will use the following format.

a[0] => 1

a[1] => 2

a[2] => 3

a[3] => 4

a[4] => 5

a[5] => 6

a[6] => 7

a[7] => 8

a[8] => 9

a[9] => 10

Remember, the index starts at 0. We will use a for-in loop also to loop through the given array:

for i in a

print a[i]

Which will give us the values from 1 to 10.

Array Representation

Arrays can be declared in various ways in different languages. Below is an illustration.

As per the above illustration, following are the important points to be considered.

  • Index starts with 0.
  • Array length is 10 which means it can store 10 elements.
  • Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.

Length of an Array

The len() method returns the length of an array i.e. the number of elements in an array. 

Example

Return the number of elements in the phones array:

  • x = len(phones)

Creating Arrays/ How to Declare Arrays in Python

Before declaring arrays, it is required to import the array module. For instance, take a look at the following code snippet:

  • import array as ar1
  • a = ar1.array(‘d’, [1.2, 2.2, 2.4, 4.6])
  • print (a)

Output:

array(‘d’, [1.2, 2.2, 2.4, 4.6])

We’ve created an array of float type after importing the array module. The letter ‘d’ is a type code that determines the type of array during creation. Following are some of the most important array type codes in Python:

  • ‘b’ – signed char
  • ‘B’ – unsigned char
  • ‘d’ – double
  • ‘f’ – float
  • ‘h’ – signed short
  • ‘H’ – unsigned short
  • ‘i’ – signed int
  • ‘I’ – unsigned int
  • ‘l’ – signed long
  • ‘L’ – unsigned long

Accessing Array Elements in Python

Indices are used for accessing elements of an array in Python. Like lists, the index starts from 0. For example:

  • import array as ar1
  • a = ar1.array (‘i’, [22, 24, 46, 53])
  • print(“The first element of the array:”, a[0])
  • print(“The second element of the array:”, a[1])
  • print(“The last element of the array:”, a[2])

Output:

The first element of the array: 22

The second element of the array: 24

The last element of the array: 53

Slicing Arrays in Python

By using the slicing operator (:), it is possible to access a range of elements present in an array in Python programming language. Following code snippet demonstrates using the slicing operator with an array in Python:

  • import array as ar1
  • number_list = [2, 4, 22, 25, 24, 52, 46, 5]
  • number_array = ar1.array(‘i’, number_list)
  • print(numbers_array[2:5]) # third to fifth
  • print(numbers_array[:-5]) # beginning to forth
  • print(numbers_array[5:]) # sixth to end
  • print(numbers_array[:]) # beginning to end

Output:

array(‘i’, [22, 25, 24])

array(‘i’, [2, 4, 22, 25])

array(‘i’, [46, 5])

array(‘i’, [2, 4, 22, 25, 24, 52, 46, 5])

Adding or Changing Elements

Arrays are mutable. Hence, their elements can be changed in a similar way as lists. Consider the following code sample:

  • import array as ar1
  • numbers = ar1.array(‘i’, [1, 2, 3, 4, 6, 10])
  • numbers[0] = 0 # replacing the first element 1 with 0
  • print(numbers)
  • numbers[2:5] = arr.array(‘i’, [4, 6, 8]) # changing third,
fourth, and fifth elements
  • print(numbers)
  • Output:

    array(‘i’, [0, 2, 3, 4, 6, 10])

    array(‘i’, [0, 2, 4, 6, 8, 10])

    The append() method is used for adding one element to an array while the extend() method allows adding multiple elements. These new elements are added to the end of the array. Observe the following code snippet:

    • import array as ar1
    • numbers = ar1.array(‘i’, [1, 2, 3])
    • numbers.append(4) # adds 4 to the array at the last position
    • print(numbers)
    • numbers.extend([5, 6, 7]) # appends iterable to the end of the array
    • print(numbers)

    Output:

    array(‘i’, [1, 2, 3, 4])

    array(‘i’, [1, 2, 3, 4, 5, 6, 7])

    The concatenation operator (+) is used for concatenating two arrays in Python programming language. For example:

    • import array as ar1
    • odd = ar1.array(‘i’, [11, 33, 55])
    • even = ar1.array(‘i’, [22, 44, 66])
    • numbers = ar1.array(‘i’) # creates an empty array of integer
    • numbers = odd + even
    • print(numbers)

    Output:

    array(‘i’, [11, 22, 33, 44, 55, 66])

    Deleting Elements from an Array

    The del statement can be used for removing one or more elements from an array in Python. For instance:

    • import array as ar1
    • number = ar1.array(‘i’, [11, 22, 33, 33, 44])
    • del number[2] # removes the third element
    • print(number)
    • del number # deletes the entire array
    • print(number)

    Output:

    array(‘i’, [11, 22, 33, 44])

    Error: array is not defined

    While the remove() method can be used for removing a specific element from the array, the pop() method allows for removing a specific element and display it. Use of both these methods are illustrated in the following code snippet:

    • import array as ar1
    • numbers = ar1.array(‘i’, [10, 11, 12, 12, 13])
    • numbers.remove(12)
    • print(numbers)
    • print(numbers.pop(2))
    • print(numbers)

    Output:

    array(‘i’, [10, 11, 12, 13])

    12

    array(‘i’, [10, 11, 13])

    Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    Searching an Element in Array

    Based on the index or value of the element, it is possible to search for the same in an array. The index() method is used for searching an element in an array based on its value. The method returns the index of the element being searched. For instance:

    • import array as ar1
    • numbers = ar1.array(‘i’, [10,20,30,40,50])
    • print (array1.index(40)) # returns the index of the element 40

    Output:

    3

    In case there is no such element that is being searched in an array, the program will give out an error.

    Array Methods

    These are the various inbuilt methods in Python for using with arrays:

    • append()Adds an element at the end of the array list
    • clear() – Eliminates all elements from the array list
    • copy() – Returns a copy of the array list
    • count() – Returns the elements along with their total number
    • extend() – Add the elements of an array list to the end of the current list
    • index() – Returns the index of the first element in an array list with the specified value
    • insert() – Adds an element to the specified position in the array list
    • pop() – Removes an element from the specified position
    • remove() – Eliminates the first element with the specified value
    • reverse() – Reverses the order of an array list
    • sort() – Sorts the array list

    Advantages of using an Array

    • Arrays can handle very large datasets efficiently
    • Computationally-memory efficient
    • Faster calculations and analysis than lists
    • Diverse functionality (many functions in Python packages). With several Python packages that make trend modeling, statistics, and visualization easier.

    Conclusion

    Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays.

    Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses