-
Hajipur, Bihar, 844101
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
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 |
print(numbers[0]) # 1
print(numbers[2]) # 3
for num in numbers:
print(num)
numbers.append(5) # Add at end
numbers.insert(1, 10) # Insert at index 1
numbers.remove(2) # Remove value
numbers.pop() # Remove last item
print(len(numbers)) # 5
numbers[0] = 100
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 |
Practice creating arrays, adding/removing elements, and using array methods.
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.
Q1: Which module is required for using arrays in Python?
Q2: What is the type code for integers?
Q3: Which method adds a value to the end of the array?
Q4: What does remove() do?
Q5: What will array[0] = 10 do?
Q6: What does pop() remove?
Q7: How to get number of elements in an array?
Q8: What method joins two arrays?
Q9: Can arrays contain mixed data types?
Q10: What does reverse() do?