Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Why use an array in python ?

An array is used to store one value at a time.Array are an important data structure for any programming
language .Python uses arrays to store collection of similar data,saving space and time.

Creating an Array in python


In Python, you can create an array-like structure using a list. Here's how you can create a list:
python
my_list = [1, 2, 3, 4, 5]
In this example, my_list is a list that contains the integers 1 through 5. Lists in Python are
versatile and can hold elements of different data types.
You can also create an empty list and then add elements to it later:

python
empty_list = []
empty_list.append(1)
empty_list.append(2)
empty_list.append(3)
Now, empty_list contains the elements 1, 2, and 3.

Accessing the element of an Array:


To access an array element ,you need to specify the index number.Indexing starts at 0 not at 1.
Hence ,the index number is always one less than the length of the array.We can access the
elements of an array using the index operator [].
Example;
Basic array operations:
 Extend element from array
If you want to extend (add) an element to a list in Python, you can use the append () method or
the extend () method.
Here's an example using

 Counting element in array


In order to count elements in an array we need to use count method.
Program;
import array
my_array = array.array('i', [1, 2, 3, 4, 2, 5, 2])
count = my_array.count(2)
print("Number of occurrences of 2:", count)
Output
Number of occurrences of 2: 3
 Deletion operation
Array element can be removed by using remove() or pop().

Example;

 Reversing the element


To reverse the elements of a list in Python, you can use the reverse() method or use slicing.
Here are example
Both methods achieve the same result, but the reverse() method modifies the original list in-
place, while slicing creates a new reversed list.

 Array concatenation
Two array can be combined by using the + operator.
Example;

You might also like