π§ͺ 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
100
is 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
for
andwhile
with 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
array
module 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 :