Python Arrays

What is an Array in python?

Python arrays are powerful data structures that allow you to store and access data in a very efficient way.

They are similar to lists, but they have some important differences.

First, let’s take a look at the different ways you can create an array in Python.

1. Create an empty array

To create an empty array in Python, we use the `array()` function with no arguments.

`my_array = array()`

2. Create an array from a list

You can also create an array in Python by providing a list of values to the `array()` function.

`my_array = array([1,2,3,4,5])`

3. Create a multidimensional array

You can also create a multidimensional array in Python by providing a nested list of values to the `array()` function.

`my_array = array([[1,2,3],[4,5,6]])`

Now that we know how to create arrays, let’s take a look at some of the different ways we can access elements in an array.

4. Access an element in an array

We can access elements in an array using indexing. Indexing starts at 0.

`my_array = array([1,2,3,4,5])`

`my_array[0]` # returns 1

`my_array[1]` # returns 2

`my_array[4]` # returns 5

We can also use negative indexing to access elements from the end of the array.

`my_array[-1]` # returns 5

`my_array[-2]` # returns 4

5. Access a multidimensional array

We can also use indexing to access elements in a multidimensional array.

`my_array = array([[1,2,3],[4,5,6]])`

`my_array[0][0]` # returns 1

`my_array[0][1]` # returns 2

`my_array[1][0]` # returns 4

Now that we know how to create and access elements in an array, let’s take a look at some of the different ways we can modify an array.

6. Add an element to an array

We can use the `append()` function to add an element to the end of an array.

`my_array = array([1,2,3,4,5])`

`my_array.append(6)`

`my_array` # returns array([1, 2, 3, 4, 5, 6])

7. Remove an element from an array

We can use the `remove()` function to remove an element from an array.

`my_array = array([1,2,3,4,5])`

`my_array.remove(3)`

`my_array` # returns array([1, 2, 4, 5])

8. Sort an array

We can use the `sort()` function to sort an array.

`my_array = array([3,2,1,5,4])`

`my_array.sort()`

`my_array` # returns array([1, 2, 3, 4, 5])

Now that we know how to create, access, and modify arrays, let’s take a look at some of the different operations we can perform on arrays.

9. Add two arrays

We can use the `+` operator to add two arrays.

`array1 = array([1,2,3])`

`array2 = array([4,5,6])`

`array1 + array2` # returns array([5, 7, 9])

10. Multiply an array

We can use the `*` operator to multiply an array.

`array1 = array([1,2,3])` `array2 = array([4,5,6])`

`array1 * array2` # returns array([4, 10, 18])

Leave a Reply