How to make an array in Python
Learn how to create an array in Python with an example, plus learn some of the most common array operations.
Creating an Array in Python
In Python, an array can be created using the array
module. The array module allows you to create an array with a specified data type, such as int
, float
, or str
. The syntax for creating an array is as follows:
import array
arr = array.array(data_type, [elements])
Where data_type
is the type of data you want to store in the array, and elements
is a list of elements you want to store in the array. For example, if we wanted to create an array of integers with the values 1, 2, and 3, the code would look like this:
import array
arr = array.array('i', [1, 2, 3])
If we wanted to create an array of strings with the values "hello", "world", and "foo", the code would look like this:
import array
arr = array.array('u', ["hello", "world", "foo"])
Once the array has been created, you can access, modify, and add elements to it. To access an element in the array, you can use the index
operator, []
. For example, to access the third element in the array above, you would use the following code:
arr[2]
Which would return the value "foo". To modify an element, simply assign a new value using the same index
operator. For example, to set the third element to "bar", you would use the following code:
arr[2] = "bar"
To add an element to the array, you can use the append()
method. For example, to add the string "baz" to the array, you would use the following code:
arr.append("baz")
And that's all there is to creating and manipulating an array in Python!