In this article, we will discuss on the array used in Python. The following contents are of this article :
- What is an array?
- Access the Elements of an Array
- The Length of an Array
- Adding Array Elements
- Removing Array Elements
- Loop in Array
- Array Methods
What is an Array?
The array can store a list of elements of similar data type. Array can store more than one values under the same array name.
Access the Elements of an Array
Elements of array can be accessed by indexing them.
flower[0]= "Rose"
print(flower)
We should know about the fact that the indexing of an array starts from 0.
The Length of an Array
To determine the length of an array we use len(). To know more you can refer to this this.
flowers = ["Rose", "Jasmine", "Tulip"]
print(len(flower)) #returns 3
Adding Array Elements
We use the method append() to add an element to the array.
flowers = ["Rose", "Jasmine", "Tulip"]
flower.append("Sunflower")
print(flowers) #returns ['Rose', 'Jasmine', 'Tulip', 'Sunflower']
Removing Array Elements
In order to remove an element from the array, we use pop() and remove() methods.
flowers = ["Rose", "Jasmine", "Tulip"]
flowers.remove("Jasmine")
print(flowers) #returns['Rose', 'Tulip']
In the pop() method we only need the index of the element that should be removed.
flowers = ["Rose", "Jasmine", "Tulip"]
flowers.pop(1)
print(flowers) #returns['Rose', 'Tulip']
Loop in Array
We can use for loop in to introduce loop in array
flowers = ["Rose", "Jasmine", "Tulip"]
for x in flowers:
print(flowers)
Array Methods
There are built-in methods in array :
- append()
- count()
- copy()
- extend()
- clear()
- pop()
- remove()
- reverse()
- sort()
- index()
- insert()