Arrays are an important data structure in computer programming. They are used to store a collection of elements of the same datatype in contiguous memory locations. In Python, we can create arrays using the built-in array
module.
To use the array
module, we need to import it first:
import array
Next, we can create an array by providing the datatype and the initial values:
my_array = array.array('i', [1, 2, 3, 4, 5])
In the above example, we have created an array of integers with the initial values of 1, 2, 3, 4, and 5.
We can access the elements of the array using indexing. The index of the first element is 0, and the index of the last element is the length of the array minus one. For example:
print(my_array[0]) # Output: 1
print(my_array[4]) # Output: 5
We can also modify the elements of the array using indexing:
my_array[2] = 10
print(my_array) # Output: array('i', [1, 2, 10, 4, 5])
In addition to creating arrays of integers, we can also create arrays of other datatypes such as characters, floats, and doubles. The following table shows some of the supported datatype codes:
Datatype | Code |
---|---|
Integer | 'i' |
Float | 'f' |
Double | 'd' |
Character | 'c' |
To create an array of a different datatype, we just need to replace the 'i' in the array creation with the appropriate code.
Arrays are a useful tool for storing and manipulating data, and Python's built-in array
module provides a simple and efficient way to work with arrays in your programs.
asdf
Top Tutorials
Related Articles