Features for Array in Python

There are several features of an array in Python that make them very easy to work with.

We will now go look at a few features of arrays. For example, some standard problems are to search through an array or perhaps to sum all the values in an array.

DIFFERENT DATA TYPES IN AN ARRAY IN PYTHON

The values in an Array do not have to be of the same data type. You can mix different data types in the same list. For example, you can have int, strings and lists in the same list! This is a major difference compared to other major programming languages, such as Java, where you need to keep track of the data type an Array contains since you cannot mix data types.

 

But now we are focusing on Array in Python so let’s take a look at how we can create a Array that contains an Integer, Text String and another Array inside it.

 

my_list3 = [2, "Python", "Python", 23, [3, 5, 10]]

And if we decide to print the results

 

print(my_list3)

 

we get:

 

[2, 'Python', 'Python', 23, [3, 5, 10]]

Useful features for an Array in Python

Arrays in Python have several built-in features which makes it very easy to work with. Below are some of the most common features of arrays.

 

Suppose we have the same array, called my_list,  in the following example

 

my_list = [5, 2, 8, 9, 3]

Size of the Array

The size of a Array can be retrieved by using the built-in function, len() 

 

len(my_list)

Results in:

 

5

Since the Array contains 5 elements.

PRINT MULTIPLE VARIABLES IN AN INTERVAL

By simply typing

 

print(my_list[2:4])

we will get the result

 

[8,9]

 

Note, the value at index 4 is not printed. In other word, typing for example print(2:4) will print ut to 4, but not include index 4.

Change the value of an element

Okay, let’s say that we want to modify the value in our Array, we simply write:

 

my_list[1] = 999

And if we then print the result we see that

 

[5, 999, 8, 9, 3]

the value at index 1 has changed from 2 to 999.

Add new values to the array

By using the built-in function append() you can easily add new values to your Array. 

 

Let’s add the value 13 to our Array

 

my_list.append(13)
print(my_list)

Results in

 

[5, 999, 8, 9, 3, 13]

 

Note, that the value is added at the end of the Array