Why use Arrays in Python?
A combination of Arrays, together with Python could save you a lot of time. As mentioned earlier, arrays help you reduce the overall size of your code, while Python helps you get rid of problematic syntax, unlike other languages. For example: If you had to store integers from 1–100, you won’t be able to remember 100 variable names explicitly, therefore, you can save them easily using an array.
What is an Array?
An array is basically a data structure which can hold more than one value at a time. It is a collection or ordered series of elements of the same type.
Syntax to Create an Array in Python
You can declare an array in Python while initializing it using the following syntax.
arrayName = array.array(type code for data type, [array,items])
The above code creates an array having integer type. The letter ‘d’ is a type code.
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.
Following are the basic operations supported by an array :
- Traverse − print all the array elements one by one.
- Insertion − Adds an element at the given index.
- Deletion − Deletes an element at the given index.
- Search − Searches an element using the given index or by the value.
- Update − Updates an element at the given index.
Python has a set of built-in methods that you can use on lists/arrays.