Python Arrays


In Python, you can use arrays with the array module when working with data of the same type.

While lists are more common, arrays are useful for performance in large datasets.


🔹 Import Array Module

import array

🔹 Create an Array

import array

numbers = array.array("i", [1, 2, 3, 4])
print(numbers)

Note: "i" stands for integer. Other type codes include:

Code Type
'i' Integer
'f' Float
'd' Double
'u' Unicode char

🔹 Access Array Elements

print(numbers[0])  # 1
print(numbers[2])  # 3

🔹 Loop Through Array

for num in numbers:
    print(num)

🔹 Add Elements

numbers.append(5)         # Add at end
numbers.insert(1, 10)     # Insert at index 1

🔹 Remove Elements

numbers.remove(2)   # Remove value
numbers.pop()       # Remove last item

🔹 Get Length

print(len(numbers))  # 5

🔹 Update Item

numbers[0] = 100

🔹 Array Methods

Method Description
append() Adds element to the end
insert() Adds at specified index
remove() Removes value
pop() Removes last element
reverse() Reverses the array
extend() Adds elements from another array

🧪 Try It Yourself

Practice creating arrays, adding/removing elements, and using array methods.


Practice Questions

Q1. Write a Python program to create an array of integers with values 1 to 5 using the array module.

Q2. Write a Python program to print the third element of the array.

Q3. Write a Python program to append the number 6 to the array using append().

Q4. Write a Python program to insert the number 10 at index 2 using insert().

Q5. Write a Python program to remove the number 2 from the array using remove().

Q6. Write a Python program to pop the last item from the array using pop().

Q7. Write a Python program to replace the first element of the array with 99.

Q8. Write a Python program to loop through the array and print each number.

Q9. Write a Python program to find the length of the array using len().

Q10. Write a Python program to use reverse() to reverse the array order.


Python Arrays Quiz

Q1: Which module is required for using arrays in Python?

A. list
B. array
C. set
D. tuple

Q2: What is the type code for integers?

A. "f"
B. "i"
C. "d"
D. "s"

Q3: Which method adds a value to the end of the array?

A. insert()
B. append()
C. push()
D. add()

Q4: What does remove() do?

A. Deletes by index
B. Removes last item
C. Removes by value
D. Clears array

Q5: What will array[0] = 10 do?

A. Replace first item
B. Add 10
C. Error
D. Delete 0

Q6: What does pop() remove?

A. First item
B. All items
C. Last item
D. None

Q7: How to get number of elements in an array?

A. count()
B. size()
C. len()
D. length()

Q8: What method joins two arrays?

A. concat()
B. append()
C. add()
D. extend()

Q9: Can arrays contain mixed data types?

A. Yes
B. No
C. Only if using list instead of array
D. Only in Python 2

Q10: What does reverse() do?

A. Removes values
B. Clears array
C. Reverses element order
D. Sorts array

Go Back Top