Arrays in Python
Some Array Commands in Python
# declaring and initializing an array
my_array = [1, 2, 3, 4, 5]
# accessing array elements
print(my_array[0]) # prints 1
print(my_array[2]) # prints 3
# updating array elements
my_array[1] = 7
print(my_array) # prints [1, 7, 3, 4, 5]
# iterating over array elements
for element in my_array:
print(element)
In this example, we declare and initialize an array called my_array
with five elements: 1, 2, 3, 4, and 5. We then print the first and third elements of the array, update the second element to 7, and print the entire array using the print
function.
Finally, we use a for
loop to iterate over each element in the array and print it to the console.