[PyTUT 5] ARRAYS IN PYTHON

Hi everyone, in this tutorial, I want to introduce another type of data in Python – array.

Related topics

Before beginning this tutorial, I recommend you should read the following topics:

[PyTUT 2] NUMBERS AND OPERATORS

[PyTUT 3] STRINGS

[PyTUT 4] VARIABLES AND COMMENTS

If you have already read these, let’s start to know what is array and what is it used for?

Introduction

Some of you may know that array is an useful type of data that permits programmers to store sets of information in one variable and to do the same thing with each element of it. This helps you to avoid making a lot of duplicated code. For example, assume that you want to store test scores of 5 students and then calculate the average test score of them. So, how could you do that? Here is 2 ways, let’s open IDLE and follow me.

Code 1

>>> student1 = 7.5
>>> student2 = 9.0
>>> student3 = 8.5
>>> student4 = 8.5
>>> student5 = 10.0
>>> average_score = (student1 + student2 + student3 + student4 + student5)/5
>>> print average_score
8.7

Well, everything seem to be more effective when using array.

Code 2

>>> student_scores = [7.5, 9.0, 8.5, 8.5, 10.0]
>>> average_score = sum(student_scores)/len(student_scores)
>>> print average_score
8.7

OK, in the example above, you saw how useful is it when using array instead of declaring a lot of variables. And it will be more effective to use array when the number of students (in the example) increase to n, with n is extremely large.

Now, let’s continue to know how to create an array in Python.

If you used to program in C/C++ or other compiled programming languages such as Java and C# before, you could know the popular structure below to create an array:

type variable_name = {value 1, value 2, value 3, ... , value n}

The compiled programming languages use braces {} to declare array of values, and you have to put the ‘type of variable’ before ‘variable’s name’. And of course, because the array have its type, the values in which must respect to the type of the array. It means if you declare the type of array string, all values in array must be string data type. Similarly, you must put integer (or float) values into your array, if you declare its type integer (or float). It sounds a bit complicated.

In Python, you don’t have to declare array data type. Instead of that, Python will consider the array data type by looking at the type of the value in array. Moreover, you can put any type of value in an array (like the code below). What a powerful weapon!

>>> iron_man = ['Tony Stark', 38, 1.82, 83, 'billionaire', 'play-boy']

However, there are some discrepancies between Python arrays depending on which kind of arrays you use. Let’s take a look through typical types of array in Python.

List

  • Creating a list

In Python, we use square bracket [] to make a list and commas to separate individual elements. For example:

>>> student_name = ['harry potter', 'ron westly', 'hermione granger']
>>> student_weight = [54, 60, 43]
  • List index

Index is an essential part of array. It is used to access elements in an array. For example, accessing the score of the third student in ‘student_scores’ array from previous example.

>>> print student_scores[2]
>>> 8.5

Remember that, index is counted from 0, so you use index 0 for the first element, 1 for the second one, 2 for the third one, and so forth.

On the other hand, you can use a negative number to be an index of a list. In this case, the index will be counted from the right, begin from -1.

>>> print student_scores[-1] 
>>> 10.0
>>> print student_scores[-2] 
>>> 8.5

In addition, you can access more than one elements from the index m to (n-1) by using the structure below:

>>> print array_name[m, n]

For example:

>>> print student_scores[1:3]
>>> [9.0, 8.5]
  • Updating an element in a list

To update an element in a list, you just simply call its index in the list and change its value. Look at the example below to see how is the score of the third student changed.

>>> print 'The score of the third student is: %.1f' %student_scores[2]
>>> The score of the third student is: 8.5
>>> student_score[2] = 9.5
>>> print 'The new score of the third student is: %.1f' %student_scores[2]
>>> The new score of the third student is: 9.5
  • Deleting an element in a list

There are many ways to delete an element in a list. You can delete an element by using ‘del’ command as the example below:

>>> print student_scores
>>> [7.5, 9.0, 9.5, 8.5, 10.0]
>>> del student_scores[2]
>>> print student_scores
>>> [7.5, 9.0, 8.5, 10.0]

Or you can use the built-in methods ‘remove’ to delete an element if you want to delete the exact value that you knew in the list. In the example below, I want to delete the value 7.5 in the list ‘student_scores’.

>>> print student_scores
>>> [7.5, 9.0, 8.5, 10.0]
>>> student_scores.remove(7.5)
>>> print student_scores
>>> [9.0, 8.5, 10.0]
  • Adding an element into a list

To add an element into a list, we use append() which is a built-in methods of list to add the element into the end of the list.

>>> print student_scores 
>>> [9.0, 8.5, 10.0]
>>> student_scores.append(9.5)
>>> print student_scores 
>>> [9.0, 8.5, 10.0, 9.5]

On the other hand, you can use insert() which is also a built-in methods of list to add the element into any position you want in the list.

>>> print 'The score of the third student is: %.1f' %student_scores[2]
>>> 10.0
>>> student_scores.insert(8.0, 2)
>>> print 'The score of the new third student is: %.1f' %student_scores[2]
>>> 8.0
  • Basic List Operations

Similar to strings, we can use addition operator + and multiplication operator * to concatenate and repeat lists, respectively.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
>>> [1, 2, 3, 4, 5, 6]
>>> d = a*3
>>> print d
>>> [1, 2, 3, 1, 2, 3, 1, 2, 3]
  • Useful Built-in methods for number list

Now, you are able to do a lot of things with lists. However, I want to show you a little further with some useful built-in methods which are often used to treat a list of number. I will illustrate these methods with the ‘student_scores’ example above.

>>> print 'The number of student:'
>>> The number of student:
>>> print len(student_scores)
>>> 5
>>> print 'The highest score:'
>>> The highest score:
>>> print max(student_scores)
>>> 10.0
>>> print 'The student who have the highest score: '
>>> The student who have the highest score:
>>> print 'Student number %d' %(student_scores.index(max(student_scores))+1)
>>> Student number 4
>>> print 'The lowest score:'
>>> The lowest score
>>> print min(student_scores)
>>> 8.0
>>> print 'The student who have the lowest score:'
>>> The student who have the lowest score:
>>> print 'Student number %d' %(student_scores.index(min(student_scores))+1)
>>> Student number 3
>>> print 'The number of student who get 9.0 in the examination: '
>>> The number of student who get 9.0 in the examination:
>>> print student_scores.count(9.0)
>>> 1
>>> print 'The order of the scores from low to high'
>>> The order of the scores from low to high
>>> print student_scores.sort()
>>> [8.0, 8.5, 9.0, 9.5, 10.0]
  • Dimension of a list

In the previous examples, we created 1D dimension list, now try to create a higher dimension list by adding a list into another lists.

>>> 1d_list = [1, 2, 3] # 1D list with shape [3]
>>> 2d_list = [[1, 2, 3], [4, 5, 6]] # 2D list with shape [2, 3]
>>> 3d_list = [[[1], [2], [3]], [[4], [5], [6]]] # 3D list with shape [2, 3, 1]
>>> print 3d_list[0][1][0]
>>> 2

High dimension lists seem to be unfamiliar now, but you will probably work a lot with it in the future if you expect to work in the field of image processing.

Tuple

Tuple is known as immutable list. It means you cannot change, append or delete the value of elements in tuple.

To declare a tuple, we use parentheses () instead of square brackets [].

>>> countries = ('Vietnam', 'America', 'Germany', 'France', 'Canada')
>>> first_eleven_fibonacci_number = (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)

Most built-in methods or operations which are used in list can also be used in tuple.

>>> print max(first_eleven_fibonacci_number)
>>> 89
>>> print sum(first_eleven_fibonacci_number)
>>> 232
>>> k = countries + first_eleven_fibonacci_number
>>> print k
>>> ('Vietnam', 'America', 'Germany', 'France', 'Canada', 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)

However, as I mentioned before, you cannot change, append or delete in tuple. If you try to do it, you will get errors.

>>> first_eleven_fibonacci_number[4] = 99

Traceback (most recent call last):
 File "<pyshell#39>", line 1, in <module>
 first_eleven_fibonacci_number[4] = 99
TypeError: 'tuple' object does not support item assignment
>>> del first_eleven_fibonacci_number[7]

Traceback (most recent call last):
 File "<pyshell#40>", line 1, in <module>
 del first_eleven_fibonacci_number[7]
TypeError: 'tuple' object doesn't support item deletion

Dictionary

In the final section, I would like to introduce another type of arrays in Python – dictionary.

pytut5

Fig. 1 Structure of a dictionary

A dictionary which is declared by using braces {} include keys and values as Fig. 1. The keys are used to connect to and access values. The values can be numbers, strings, lists, or even dictionaries.

>>> satre = {'name': 'Jean-Paul Satre', 'aged': 74, 'country': 'France', \
             'works': ['Le mur', 'Les mouches', 'Le sursis']}
>>> print '%s died in Paris, France, aged %d' %(satre['name'], satre['aged'])
>>> Jean-Paul Satre died in Paris, France, aged 74
>>> print 'Three of his famous books are:'
>>> Three of his famous books are:
>>> print satre['works'][0]
>>> Le mur
>>> print print satre['works'][1]
>>> Le mouches
>>> print print satre['works'][2]
>>> Le sursis

Most things you can do with lists and tuples, you can also do with dictionaries but you need to use key instead of index.

>>> print 'Deleting Satre's age'
>>> Deleting Satre's age
>>> del satre['age']
>>> print 'The amount of information about Satre: %d' %len(satre)
>>> The amount of information about Satre: 3

However, you cannot use operator such as + or * for dictionaries as lists and tuples. On the other hand, to add a new key-value into the dictionary, you cannot use append() method. Instead, you can do this.

>>> satre['philosophy'] = 'Existentialism'

So, with all basic things I introduced, you are now able to do a lot of things with arrays in Python. In the next tutorial, I will introduce control structures and we will try writing the first script in Python.

 

Hope you enjoy it,

Curious Chick

Advertisements

Author: curiouschick

There are many things you may never know about me. But, two things you absolutely know when you visit my blog for the first time: I am a chick and really curious to know everything.

One thought on “[PyTUT 5] ARRAYS IN PYTHON”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s