define an array in python

To define an array in Python, you can use the built-in array module or simply use a list.

Here is an example of defining an array using the array module:

main.py
import array

# create an array of integers
my_array = array.array('i', [1, 2, 3, 4, 5])

# print the array
print(my_array)
124 chars
8 lines

Output:

main.py
array('i', [1, 2, 3, 4, 5])
28 chars
2 lines

In the above example, we imported the array module and then used the array() function to create an array of integers. The first argument to the array() function is the type code ('i' for integers) and the second argument is a list of values to be stored in the array.

Alternatively, you can define a list and use it as an array in Python:

main.py
# create an array using a list
my_array = [1, 2, 3, 4, 5]

# print the array
print(my_array)
93 chars
6 lines

Output:

main.py
[1, 2, 3, 4, 5]
16 chars
2 lines

In the above example, we created a list of values and treated it as an array. This is because Python does not have a built-in array data type, but lists can be used as arrays in most cases.

gistlibby LogSnag