Skip to main content

Python Arrays: Definition, Types, and Examples

 

✍️Introduction

An array is used to store multiple values in a single variable instead of creating separate variables for each value. Arrays help organize data efficiently and make it easier to perform operations on large sets of values.

In Python, arrays are mainly used when we want to store elements of the same data type and perform fast calculations.

Arrays are different from lists because arrays store only similar data types (like all integers or all floats), while lists can store mixed data types. Python provides arrays through the array module and also through libraries like NumPy for advanced operations.

Arrays are useful when:

  • Working with large amounts of numerical data

  • Performing calculations quickly

  • Saving memory compared to lists

  • Processing data in loops

Arrays are commonly used in scientific computing, data analysis, and real-world applications where efficient data storage and processing are required.


Are Arrays Available in Python?

Python does not have traditional built-in arrays like C or Java, but Python provides other ways to store multiple values in a single variable. These alternatives work like arrays and are commonly used in Python programs.

In Python, we can use the following instead of traditional arrays:

  1. List : Most commonly used and flexible

  2. array module : Stores same type of data

  3. NumPy arrays : Used for advanced calculations

👉 In this article, we focus on Python array module for beginners.

Import Array Module :

Before using arrays in Python, we must import the array module.
The array module provides a way to store multiple values of the same data type in a single variable.

Python does not support arrays directly, so we use the array module to create and work with arrays.

import array # Imports the array module so we can create arrays

Note:We must import the array module before creating an array in Python.


Create an Array in Python :

An array is a collection of elements of the same data type stored in a single variable.

In Python, arrays are created using the array module.
We must specify a typecode that tells Python what type of data the array will store (like integers or floats).
Arrays are more memory-efficient than lists when storing large numeric data.

Syntax:

array.array(typecode, elements)

  • typecode → Defines data type (e.g., 'i' for integers)
  • elements → Values stored in the array

Example:

import array as arr # Import array module and rename it as arr numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array with values print(numbers) # Print the array

Output:
array('i', [10, 20, 30, 40])

"Code executed successfully" 

Note:

✔ All elements in an array must be of the same data type. ✔ 'i' typecode is used for integers.



Common Array Type Codes :

Type codes in Python arrays define the type of data the array can store.
Each type code represents a specific data type like integer or float.
Using correct type codes ensures memory efficiency and faster processing.

Following are common array type codes:

Type Code                  Data Type             
    iInteger
   f                             Float
  dDouble
  uUnicode character

Access Array Elements:

Accessing array elements means retrieving values from an array using their index position.

In Python arrays, indexing starts from 0.
The first element is at index 0, the second at 1, and so on.
We use square brackets [] to access elements.

Example:

import array as arr # Import the array module and give it a short name 'arr' numbers = arr.array('i', [10, 20, 30, 40]) # Create an array of integers with values 10, 20, 30, 40 print(numbers[0]) # Print the first element of the array (index starts at 0) print(numbers[2]) # Print the third element of the array (index 2)


Output:
10 30

"Code executed successfully" 

Note:Index always starts from 0, so numbers[0] is the first element.


Change Array Elements :

Changing array elements means updating the value of an existing element at a specific index in the array.

  • Arrays in Python are mutable, which means their values can be changed after creation.

  • We can modify an element by using its index number.

  • Indexing starts from 0, so the second element is at index 1.

Example:

import array as arr # Import the array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers[1] = 25 # Change the element at index 1 (20 → 25) print(numbers) # Print updated array

Output:
array('i', [10, 25, 30, 40])

"Code executed successfully" 

Note:We use array[index] = new_value to change an element in the array.

Array Length :

Array length means the total number of elements present in an array.

  • In Python, we use the len() function to find the number of elements in an array.

  • It works with arrays, lists, strings, and other collections.

  • The length helps in loops and indexing operations.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array print(len(numbers)) # len() returns the total number of elements

Output:
4

"Code executed successfully" 

Note:len(array_name) gives the total number of elements in the array.

Loop Through Array :

Looping through an array means accessing each element one by one using a loop.

  • In Python, we commonly use a for loop to iterate through arrays.

  • The loop automatically goes through each element in order.

  • It is useful for printing, searching, or processing array elements.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array for num in numbers: # Loop through each element in the array print(num) # Print the current element


Output:
10 20 30 40

"Code executed successfully" 

Note:The for loop automatically visits each element in the array one by one.

Add Elements to Array :

Adding elements to an array means inserting new values into the array after it has been created.

  • In Python arrays, we use the append() method to add an element at the end of the array.

  • The new element must match the array data type (type code).

  • For example, if the array type is integer ('i'), only integers can be added.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.append(50) # Add 50 at the end of the array print(numbers) # Print updated array

Output:
array('i', [10, 20, 30, 40, 50])

"Code executed successfully" 

Note:append() always adds the element at the end of the array.

Remove Elements from Array :

Removing elements from an array means deleting values from the array when they are no longer needed.

  • Python arrays provide methods like remove() and pop() to delete elements.

  • remove(value) deletes a specific value from the array.

  • pop() removes the last element from the array.

  • These operations help manage and update array data easily.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.remove(20) # Removes value 20 from the array numbers.pop() # Removes the last element (40) print(numbers) # Print updated array

Output:
array('i', [10, 30])

"Code executed successfully" 

Note:

  • remove() deletes a specific value.
  • pop() deletes the last element by default.

  • If the value is not found, remove() gives an error.


Array Index Method :

The index() method is used to find the position (index) of a specific element in an array.

  • Every element in an array has a position called an index.

  • Indexing starts from 0 in Python.

  • The index() method returns the position of the first occurrence of the element.

  • If the element is not found, Python gives an error.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array print(numbers.index(30)) # Finds the index position of value 30

Output:
2

"Code executed successfully" 

Explanation:

  • 10 → index 0

  • 20 → index 1

  • 30 → index 2

  • 40 → index 3

So the index of 30 is 2.

Note:
If the value does not exist:

print(numbers.index(50))

It will give an error:

ValueError: array.index(x): x not in array

Reverse an Array :

The reverse() method is used to reverse the order of elements in an array.

  • It changes the array in-place (original array is modified).

  • The first element becomes the last, and the last becomes the first.

  • It does not create a new array, it only rearranges elements.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30, 40]) # Create an integer array numbers.reverse() # Reverse the order of elements in the array print(numbers) # Print the reversed array

Output:
array('i', [40, 30, 20, 10])

"Code executed successfully" 

Explanation:
Before reverse:
10 → 20 → 30 → 40

After reverse:
40 → 30 → 20 → 10

Note:reverse() permanently changes the original array.


Convert Array to List :

Converting an array to a list means changing the array data into a Python list format so we can use list functions.
  • Python arrays and lists are different data structures.

  • Lists are more flexible and support many built-in methods.

  • We use the list() function to convert an array into a list.

  • After conversion, we can easily modify the data.

Example:

import array as arr # Import array module numbers = arr.array('i', [10, 20, 30]) # Create an integer array list_data = list(numbers) # Convert array into list print(list_data) # Print the list

Output:
[10, 20, 30]

"Code executed successfully" 

Note:After conversion, you can use list functions like append(), remove(), and sort().

Difference Between Array and List :

Arrays and lists are both used to store multiple values, but they work differently.
Arrays store elements of the same data type, while lists can store different data types.
Arrays are generally faster and use less memory, whereas lists are more flexible and commonly used in Python.

Feature          Array                  List            
Data Type Same typeDifferent types
SpeedFasterSlower
Memory           Less                         More
UsageNumeric dataGeneral purpose

Note:Lists are used more often in Python, while arrays are mainly used for numeric calculations.

Real-Life Example :

This program stores student marks in an array and calculates the total marks.

import array as arr # Import array module marks = arr.array('i', [85, 90, 78, 88]) # Create an integer array of marks total = sum(marks) # Calculate total marks print("Total Marks:", total) # Print the total marks

Output:
Total Marks: 341

"Code executed successfully" 

Note:Arrays are commonly used in real-life applications like student result systems

and score calculations.


❌ Common Mistakes :

  • Forgetting to import array module

  • Using wrong type code

  • Adding different data type values


When to Use Arrays?

  • Mathematical calculations

  • Large numeric data

  • Performance-critical programs


Conclusion :

Python arrays are useful when you need fast and memory-efficient storage of same-type elements.
For most programs, lists are enough, but arrays are important to know.


💬 Quick Question :

What will be the output?

import array as arr a = arr.array('i', [1, 2, 3]) a.append(4) print(a)

Comment your answer 👇😊


📌 Related Articles



Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type