In this post, we're gonna learn about arrays in Python.
What is an Array?
Below, a list of the most usable definitions of an array:
- An array is a container that holds data (an ordered collection of items)
- An array is a data structure that stores values of the same data type.
- Arrays are used to store multiple values in one single variable instead of declaring separate variables for each value.
How can we access the array elements?
- Each element in an array has an index and it is accessed by this index.
- The index starts with zero and goes up one at a time and there are some programming languages like Cobol which start with index 1.
The major operations in data structure are (Access, Insert, Delete, Find, Sort) an element
Arrays in Python
- Python does not have built-in support for Arrays.
- Python lists can be used instead of arrays.
- The main difference between arrays and lists is that we cannot constrain the type of elements stored in a list example a=[1,2.4,”hello”].
- To use arrays in python language, you need to import the standard ‘array’ module
Array declaration in Python
arrayIdentifierName = array(typecode, [Initializers]
Typecodes are the codes that are used to define the type of array values.
- ‘b’ is for signed integer of size 1 byte
- ‘B’ is for unsigned integer of size 1 byte
- ‘c’ is for character of size 1 byte
- ‘u’ is for Unicode character of size 2 bytes
- ‘h’ is for signed integer of size 2 bytes
- ‘H’ is for unsigned integer of size 2 bytes
- ‘i’ is for signed integer of size 2 bytes
- ‘I’ is for unsigned integer of size 2 bytes
- ‘w’ is for Unicode character of size 4 bytes
- ‘l’ is for signed integer of size 4 bytes
- ‘L’ is for unsigned integer of size 4 bytes
- ‘f’ is for floating point of size 4 bytes
- ‘d’ is for floating point of size 8 bytes
Access an array element in Python
- We access the elements with its index that start from 0 index
Array length in Python
- Use the len() method to return the length of an array.
Looping array elements in Python
- looping the array element by using for loop
Sort arrays in Python
Using sort() you will sort the given list in ascending order.
You can set reverse= true to sort in descending order
In this post, we have learned about arrays in Python.