Python Array Exercises – Practice Problems with Solutions
Python arrays are used to store multiple values of the same type in a single variable. While Python lists are more commonly used, the array module from Python’s standard library offers memory-efficient storage and is ideal for numeric data.
In this article, you’ll find hands-on exercises, solutions, and explanations to help solidify your understanding of arrays in Python.
Introduction to Python Arrays
To use arrays in Python, import the array module:
import array
arr = array.array('i', [1, 2, 3, 4, 5])
'i' is the type code for signed integers. Other codes include 'f' for float, 'd' for double, etc.
Exercise 1: Create and Traverse an Array
Task:
- Create an array of 5 integers.
- Traverse it and print each element.
import array
arr = array.array('i', [10, 20, 30, 40, 50])
for num in arr:
print(num)
Exercise 2: Append, Insert, and Extend Arrays
Task:
- Append a number to the array.
- Insert a value at position 2.
- Extend the array with another list.
arr.append(60)
arr.insert(2, 25)
arr.extend([70, 80])
print(arr) # array('i', [10, 20, 25, 30, 40, 50, 60, 70, 80])
Exercise 3: Remove and Pop Elements
Task:
- Remove value
25. - Pop the last item.
- Try to remove an item that doesn’t exist and handle the error.
arr.remove(25) # Removes the first occurrence of 25
arr.pop() # Removes the last element
try:
arr.remove(999)
except ValueError:
print("Element not found!")
Exercise 4: Search for Elements
Task:
- Search for the index of element
30. - Check if
100is present.
index = arr.index(30)
print("Index of 30:", index)
if 100 in arr:
print("100 found")
else:
print("100 not found")
Exercise 5: Looping and Indexing
Task:
- Loop through array using
forandwhilewith index. - Print the value and index.
for i in range(len(arr)):
print(f"Index {i} = {arr[i]}")
# Using while loop
i = 0
while i < len(arr):
print(f"While Index {i} = {arr[i]}")
i += 1
Exercise 6: Reverse and Slice Arrays
Task:
- Reverse the array using slicing.
- Slice from index 2 to 5.
reversed_arr = arr[::-1]
print("Reversed:", reversed_arr)
slice_arr = arr[2:6]
print("Slice 2 to 5:", slice_arr)
Exercise 7: Array Length and Buffer Info
Task:
- Find the length of the array.
- Get memory buffer info.
print("Length:", len(arr))
print("Buffer Info:", arr.buffer_info())
buffer_info() returns a tuple (memory_address, number_of_elements)
Practice Quiz
Question 1:
What will the following code output?
import array
arr = array.array('i', [1, 2, 3, 4])
arr.insert(1, 100)
print(arr[1])
Answer: 100
Question 2:
Which method is used to add multiple elements?
- A.
insert() - B.
append() - C.
extend() - D.
pop()
Answer: C. extend()
Summary
- Python arrays using the
arraymodule are efficient for numeric data. - Basic operations include creation, traversal, insertion, removal, searching, and slicing.
- These exercises help reinforce foundational array handling before diving into advanced data structures like NumPy arrays or lists of objects.
FAQs
Q1. What’s the difference between array and list in Python?
Arrays store same-type elements (efficient for large numeric data), while lists can store mixed types.
Q2. Can I store strings in an array?
Not with the array module. For strings, use lists or specialized libraries like NumPy.
Q3. What are valid type codes for arrays?
Examples: 'i' (int), 'f' (float), 'd' (double), 'b' (signed char)
Q4. Can arrays be multidimensional in Python?
Not with array module. Use NumPy for multi-dimensional arrays.
Share Now :
