In Python, arrays are used to store multiple values of the same data type in a single variable. They come from the built-in array module and are more memory-efficient than lists when you are working with large amounts of numeric data.
array module, not built-in like lists.'i' for signed integers).To use arrays, you must first import the array module. Then you create an array by specifying a type code and an initial iterable of values:
Basic pattern:
array.array(typecode, iterable) # create an array with a type code and initial values
Common integer type codes:
'i' – signed integer'I' – unsigned integer'f' – floating point'd' – double precision floating pointFirst, import the module and create an array of integers using the appropriate type code.
import array
# Create an array of integers
numbers = array.array('i', [10, 20, 30, 40])
print(numbers) # array('i', [10, 20, 30, 40])
You can access elements by index, just like with lists. Indexing starts from 0.
print(numbers[0]) # 10
print(numbers[2]) # 30
Change the value at a specific index by assigning a new value to that position.
numbers[1] = 25 # change value at index 1
print(numbers) # array('i', [10, 25, 30, 40])
Arrays support common list-like methods such as append(), insert(), pop(), and remove().
numbers.append(50) # Add at end
numbers.insert(1, 15) # Insert at index 1
numbers.pop() # Remove last element
numbers.remove(30) # Remove specific element
print(numbers) # show final array contents
Use a for loop to visit each element in the array.
# Loop through each value in the array
for num in numbers:
print(num)
If you run all the examples in order, you will see something like this (values may vary based on your edits):
array('i', [10, 20, 30, 40])
10
30
array('i', [10, 25, 30, 40])
array('i', [10, 15, 25, 40, 50])
10
15
25
40
50
Notice how:
list over array.array.NumPy arrays for even better performance and more features.'f') and print all its elements.insert(0, value).