Python Array Example

Python array is a data structure, like list, that allow you to store multiple records of similar data type.

Like all other programming language, in python, we have array concept, syntax is almost same as JavaScript, but here we see many different ways to work with array, first let’s understand how to define an array in python.

there are different ways we can define an array in python.

Define array using range, which accept an integer as parameter.

array1 = [0 for i in range(5)] 
print(array1) 
# result 
# [0, 0, 0, 0, 0]

Creating array using combine variable.

width, height=(4,5)
box = [width,height] 
print(box) 

Define array with comma-separated values, this is most commonly used way of creating an array in all other language.

array2 = [0,1,2,3,4,5,6,7,8,9] 
print(array2) 

Here is how we can define two-dimension array in python.

array3 =[array1,array2]
print(array3)

#result 
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] 

We can also create array using array method of array module, here is an example below how you can use arr.array() method.

import array as arr
abc = arr.array('d', [1.5, 2.4, 8.9])
print(abc)

Python array methods

Here are some built-in array methods in python we often use.

  • append()

    Adds an item to an array, let's day we want to add another fruit in following fruit array.

    fruits = ["Banana", "Apple", "Orange"]
    fruits.append("Cucumber") 
    
  • pop()

    Removes an item from an array, we also can use remove method to remove an element from array.

    fruits = ["Banana", "Apple", "Orange", "Cucumber"]
    fruits.remove("Apple") 
    fruits.pop(1) // removes second element. 
    
  • clear()

    Removes all items from an array

  • copy()

    Returns a copy of an array, copy method will copy all the elements from specified array to a new array.

    fruits = ["Banana", "Apple", "Orange", "Cucumber"]
    fruits2 = fruits.copy()
    
    now  fruits2 will have all the elements as source array.
    
  • reverse()

    Reverses the order of the array

    fruits = ["Banana", "Apple", "Orange"]
    
    fruits.reverse()
     
    // result : "Orange" ,  "Apple", "Banana"
    
  • count()

    Returns the number of elements in a list

  • len()

    We can find length of an array using len method, the method returns how many element there in the array.

    array4 = [0,1,2,3,4,5,6,7,8,9] 
    n = len(array4) 
    

There is another advanced library in python called NumPy, that provides many built-in functionality to work with array object, You may be interested in following posts.

 
Array in Python
Python Array
Python programming examples | Join Python Course