Back to Python
2026-02-077 min read

Python Array

Learn Python Array step by step with clear examples and exercises.

Title: Python Array - A full guide for Practical Depth

Why This Matters

In programming, arrays are a fundamental data structure that store multiple values of the same type. Understanding Python arrays is crucial for solving complex problems, writing efficient code, and preparing for interviews or exams. Real-world scenarios frequently involve handling large amounts of data in arrays, making it essential to master this topic.

Prerequisites

To follow this lesson, you should be familiar with the basics of Python programming, including variables, operators, control structures such as if statements and loops, and basic file I/O operations. If you're new to Python, consider starting with our Getting Started With Python tutorial.

Core Concept

Python arrays are used to store a collection of elements of the same data type in contiguous memory locations. They provide an efficient way to perform operations on multiple values at once, such as sorting, searching, and manipulating data. Python uses built-in list objects to represent arrays.

Creating Arrays (Lists)

To create an array in Python, you use a list, which is a collection of items enclosed within square brackets []. Here's an example:

my_array = [1, 2, 3, 4, 5]
print(my_array) # Output: [1, 2, 3, 4, 5]

Accessing Array Elements

To access an element in a Python array (list), you use its index. The first element has an index of 0, and indices increase by 1 for each subsequent element. Here's an example:

my_array = [1, 2, 3, 4, 5]
print(my_array[0]) # Output: 1
print(my_array[4]) # Output: 5

Modifying Array Elements

To modify an element in a Python array (list), you assign a new value to the index of the element you want to change. Here's an example:

my_array = [1, 2, 3, 4, 5]
my_array[0] = 10
print(my_array) # Output: [10, 2, 3, 4, 5]

Array Length

To find the length of a Python array (list), you can use the len() function. Here's an example:

my_array = [1, 2, 3, 4, 5]
print(len(my_array)) # Output: 5

Basic Array Operations

Python arrays (lists) support several built-in methods for common operations such as sorting, searching, and manipulating data. Here are some examples:

  • Sorting: To sort a Python array (list), you can use the sort() method. Here's an example:
my_array = [5, 1, 3, 2, 4]
my_array.sort()
print(my_array) # Output: [1, 2, 3, 4, 5]
  • Searching: To find the index of a specific element in a Python array (list), you can use the index() method. Here's an example:
my_array = [1, 2, 3, 4, 5]
print(my_array.index(3)) # Output: 2
  • Adding Elements: To add elements to the end of a Python array (list), you can use the append() method. Here's an example:
my_array = [1, 2, 3]
my_array.append(4)
print(my_array) # Output: [1, 2, 3, 4]
  • Inserting Elements: To insert an element at a specific index in a Python array (list), you can use the insert() method. Here's an example:
my_array = [1, 2, 3]
my_array.insert(1, 0)
print(my_array) # Output: [1, 0, 2, 3]
  • Removing Elements: To remove an element at a specific index in a Python array (list), you can use the remove() method. Here's an example:
my_array = [1, 0, 2, 3]
my_array.remove(0)
print(my_array) # Output: [1, 2, 3]
  • Slicing: To access a subset of elements in a Python array (list), you can use slicing. Here's an example:
my_array = [1, 2, 3, 4, 5]
print(my_array[1:3]) # Output: [2, 3]

Multi-dimensional Arrays (Lists of Lists)

Python also supports multi-dimensional arrays using lists of lists. Here's an example of a 2D array:

my_array = [[1, 2], [3, 4], [5, 6]]
print(my_array) # Output: [[1, 2], [3, 4], [5, 6]]

Worked Example

Let's create a Python program that calculates the average of an array of numbers and finds the largest number in the array.

def find_average_and_max(numbers):
total = sum(numbers)
average = total / len(numbers)
max_number = max(numbers)

print("Average:", average)
print("Maximum:", max_number)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
find_average_and_max(numbers)

Output:

Average: 5.0
Maximum: 9

Common Mistakes

  1. Forgotten Index: When accessing or modifying an array element, forgetting the index can lead to errors.
my_array = [1, 2, 3, 4, 5]
print(my_array[6]) # Raises an IndexError: list index out of range
  1. Incorrect Data Type: Python lists can only store items of the same data type. Attempting to add an item of a different data type will result in a TypeError.
my_array = [1, 2, 3]
my_array[0] = "apple" # Raises a TypeError: can only concatenate list (not "str") to list
  1. Improper List Comprehension: Incorrect syntax or logic in list comprehensions can lead to unexpected results or errors.
squares = [i**2 for i in range(10)] # Correct list comprehension
cubes = [i**3 for i in range(10)] # Correct list comprehension

Incorrect list comprehension (missing square brackets)

incorrect_squares = i2 for i in range(10) # Raises a SyntaxError: invalid syntax


4. **List Comprehensions with Side Effects**: List comprehensions are meant to create lists, not modify the original list. Modifying the original list during a list comprehension can lead to unexpected results or errors.

my_array = [1, 2, 3]

my_array[0] = my_array[0] * 2 # Correct way to modify the first element of the list

Incorrect modification during list comprehension (raises a TypeError)

incorrect_modification = [i2 for i in range(10)] + [my_array[0] * 2]


5. **List Comprehensions with Loops**: Using loops within list comprehensions can lead to performance issues and should be avoided when possible.

Correct way to create a list of squares using a loop

squares = []

for i in range(10):

squares.append(i2)

Incorrect way to create a list of squares using a list comprehension with a loop

incorrect_squares = [i2 for i in range(10)] * 10 # This creates a list of 10 lists, each containing the same squares

Practice Questions

  1. Write a Python program that finds the sum of all even numbers in an array.
  2. Given an array of strings, write a Python function that sorts the array alphabetically and case-insensitively.
  3. Write a Python program that finds the second largest number in an array.
  4. Create a Python program that reverses the order of elements in an array.
  5. Write a Python function that removes duplicates from an array while preserving the original order of unique elements.
  6. Write a Python program that finds the kth smallest element in an array using quickselect algorithm.
  7. Write a Python program that finds all permutations of an array using recursion.
  8. Write a Python program that finds all subarrays with a given sum using sliding window technique.
  9. Write a Python program that finds the longest common subsequence between two arrays using dynamic programming.
  10. Write a Python program that finds the number of inversions in an array using merge sort.

FAQ

  1. How do I create an empty array (list) in Python?

You can create an empty array (list) using [] or list(). For example:

my_array = []
another_array = list()
  1. How do I find the index of a specific element in a Python array (list)?

You can use the index() method to find the index of an element in a Python array (list). Here's an example:

my_array = [1, 2, 3, 4, 5]
print(my_array.index(3)) # Output: 2
  1. How do I add elements to the end of a Python array (list)?

You can use the append() method to add an element to the end of a Python array (list). Here's an example:

my_array = [1, 2, 3]
my_array.append(4)
print(my_array) # Output: [1, 2, 3, 4]
  1. How do I insert an element at a specific index in a Python array (list)?

You can use the insert() method to insert an element at a specific index in a Python array (list). Here's an example:

my_array = [1, 2, 3]
my_array.insert(1, 0)
print(my_array) # Output: [1, 0, 2, 3]
  1. How do I remove an element at a specific index in a Python array (list)?

You can use the pop() method to remove an element at a specific index in a Python array (list). Here's an example:

my_array = [1, 0, 2, 3]
removed_element = my_array.pop(1)
print(my_array) # Output: [1, 2, 3]
print("Removed element:", removed_element) # Output: 0
  1. How do I remove the last element from a Python array (list)?

You can use the pop() method without an index to remove the last element from a Python array (list). Here's an example:

my_array = [1, 2, 3]
removed_element = my_array.pop()
print(my_array) # Output: [1, 2]
print("Removed element:", removed_element) # Output: 3
  1. How do I sort a Python array (list)?

You can use the sort() method to sort a Python array (list). Here's an example:

my_array = [5, 1, 3, 2, 4]
my_array.sort()
print(my_array) # Output: [1, 2, 3, 4, 5]
  1. How do I reverse the order of elements in a Python array (
Python Array | Python | XQA Learn