DEV Community

Saravanan
Saravanan

Posted on

Array Methods - Python

Python doesn't have a built-in array data type. The array module is used to work with the array. An array can be created as shown below.

import array

arr = array.array("i", [1, 2, 3, 4, 5])
Enter fullscreen mode Exit fullscreen mode

The above line creates an array of elements 1 to 5 of type signed integer. Here the array() function is used to create an array. The first "i" is to mention that the type code of the array is a signed integer.

The list of type codes can be obtained by running below

array.typecodes
Enter fullscreen mode Exit fullscreen mode

which returns bBuhHiIlLqQfd.

  • b - signed char
  • B - unsigned char
  • u - unicode char
  • h - signed short
  • H - unsigned short
  • i - signed int
  • I - unsigned int
  • l - signed long
  • L - unsigned long
  • q - signed long long
  • Q - unsigned long long
  • f - float
  • d - double

All the type code has a corresponding C Type. The byte size of the type depends upon the machine running the program. The byte size of arr can be checked below

arr.itemsize
Enter fullscreen mode Exit fullscreen mode

The array can be created from the list and converted to the list as below.

arr.fromlist([1, 2, 3, 4, 5])
arr.tolist() # returns python list [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

New items can be added to the array by appending or inserting a value at a position.

arr.append(6)
arr.insert(2, 2)
Enter fullscreen mode Exit fullscreen mode

New items can be appended from strings or files also.

arr.append("word")
arr.append(file_source, 10) # reads 10 lines from file and appends it
Enter fullscreen mode Exit fullscreen mode

Elements can be removed by using the index or value of the element. The pop is to remove from an element by passing the index and the remove is by passing a value of the element.

arr.pop(1)
arr.remove(4)
Enter fullscreen mode Exit fullscreen mode

The array can also be reversed by calling the reverse function. This does not reverse the array in memory but, changes the access order.

arr.reverse()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)