Create Array In Python

Python is a popular programming language that does not support the array natively. But Python provides a very similar type named List . If you need to create an array-like structure to store multiple items you can use the List. In this tutorial, we will call the list an array as it is very similar and provides very same attributes and features.

Create Array

An array can be created by using list declaration syntax. We can provide the list of items inside the square brackets by separating them with commas. In the following example, we create an array named “cities”.

cities=["London","Newyork","Istanbul","Berlin"]

Access Array Element

We can use index numbers in order to access array elements. In the following example, we get the 2nd element whose index number is 1.

cities=["London","Newyork","Istanbul","Berlin"]

print(cities[1])

Array Length

The len() function can be used to get array length. The array is provided to the len() function as a parameter.

cities=["London","Newyork","Istanbul","Berlin"]

print("Array length is ",len(cities))

Loop (Iterate) Array

We can iterate over array elements by using different loop mechanisms. The for loop can be used to loop or iterate over array elements.

cities=["London","Newyork","Istanbul","Berlin"]

for city in cities:
   print(city)

Add Array Element

The list append() method is used to add a new array element. The element we want to add is provided as a parameter to the append() method.

cities=["London","Newyork","Istanbul"]

cities.append("Berlin")

Remove Array Element

The pop() method can be used to remove or delete elements from the array. The elements index number is provided to the pop() method to remove. In the following example, we delete 3rd element whose index number is 2 which is “Istanbul”.

cities=["London","Newyork","Istanbul","Berlin"]

cities.pop(2)

Reverse Array Elements

Array elements can be reversed by using the reverse() method.

cities=["London","Newyork","Istanbul","Berlin"]

cities.reverse()

print(cities.reverse())

Leave a Comment