Linux Format

Array for Python!

Nate Drake guides you through the most fun that you can have with Python arrays while still sober and in full control of your limbs.

- Our expert Nate Drake is a freelance technology journalist. After coding the Magic 8 Ball array, the script now makes all-important life decisions for him. Outlook not so good…

Nate Drake guides you through the most fun you can have with Python while still sober.

Those readers who have any experience of grappling with the coils of the Python will already know that the programmin­g language is designed to handle data structures efficientl­y. The most basic of these is the Python list, which can be written as a sequence of comma separated values. For instance, to create a list of your favourite foods you can declare a list as follows: list1 = ['chocolate’, ‘bananas’, ‘caviar’, ‘jelly beans']

Once you’ve done this, you can easily recall values by specifying the numerical index of an item in the list. Run print(list1[0]) to display the first item in the list (in this case it’s chocolate). The process of searching for and displaying values based on the index is sometimes known as slicing.

Lists are very versatile in that you can store multiple data types such as strings and integers. You’ve also seen how easy they are to implement. If you only wish to store a list of your weekly groceries in Python, you may need nothing else. However, when it comes to processing larger amounts of data efficientl­y, Python also incorporat­es a module that enables you to create arrays.

Much like lists, arrays are a type of data sequence, although the garden variety array module in Python is designed to only hold one type of object, such as integers. You determine the kind of data the array will hold when you create it. To get started with arrays, first ensure you have python3 installed on your machine. Most popular Linux distributi­ons bundle this by default.

Get importing

Next, fire up your Terminal or IDLE (see boxout, aboveright) and import the array module with: From array import *

Next create the array myarray. This will contain only integers (specified by the type code i) from 1 to 6. myarray=array(‘i’,[1,2,3,4,5,6])

Finally, have Python list the values in the array: For i in myarray:

print(i) If you’re using IDLE, you can use F5 at this stage to run your script, otherwise save your file with a meaningful name use Terminal to run $ sudo python3 <meaningful­filename>.py .

You can also print individual values (or elements as they are known) from the array in exactly the same way as for lists, for instance run print (myarray[0]) to view the first element, which in this case is the number 1.

While you may feel a glow of success at this stage, in its current format this Python script is only useful to those coders who are unable to count past the number five. To this end, create a new file and paste in the code below. This Python script uses the secret module to add some

randomness to your slicing, turning it into a rough and ready electronic dice game: import secrets from array import * myarray=array('i’,[1,2,3,4,5,6]) roll = secrets.choice(range(0,len(myarray))) print (myarray[roll]) The value roll here is the minimum value of the myarray index (0) and the maximum length which is specified as len(arrayname) . You can use this at any time to retrieve the number of elements in a standard Python array.

Manipulati­ng arrays

While so far you’ve learned how to create and list elements in an array, you can also manipulate them while a program is running. You may wonder why you’d bother doing this when you can just stop the script and edit the code itself. However, this is useful for keeping track of data that you’ve processed and adding new informatio­n. For instance ,if you’re running a virtual casino ( seebelow) you may want to add new players and winnings, as well as keep a record of cards already played.

To insert a value in a specific position in an array, use insert. For instance myarray.insert(0,1) will set the very first element in the array to 1. This doesn’t delete existing data, because the other items will be shuffled round accordingl­y.

If you simply want to add new elements to the end of an array, you can use append, for instance: myarray.append(7)

However, if you want to add a large number of variables, you’d need to do this individual­ly for each of the new values which doesn’t make for very tidy code. A more efficient way to do things is to create a new array with all the values you’d like to append, then extend the existing array as follows: newvalues=array(‘I’,[8,9,10]) myarray.extend(newvalues)

Call on Numpy

While the standard Python array module is a great way to familiaris­e yourself with arrays, it’s difficult to use it in more advanced scenarios. For instance, there’s no quick and easy way to store string values, nor to create a multidimen­sional array (more on this later). Fortunatel­y Numpy (Numerical Python) has specifical­ly been designed for scientific computing and contains tools to enable you to create ultraeffic­ient and powerful arrays. To get started, first make sure you have the Pip installer on your machine by opening

Terminal and running: $ sudo apt-get install python3-pip Next enter the following: $ sudo pip3 install numpy

The convention for invoking the Numpy module when writing a script is import numpy as np . From there you can declare a Numpy array with np.array . One of the most immediate advantages of using Numpy to create your array is that it can automatica­lly detect the type of data you’re entering into the array such as a string or integer, enabling you to store both. In keeping with the electronic dice you created earlier, use your favourite editor to create an empty file named magic8.py and paste the following: import secrets import numpy as np myarray=np.array(['It is certain.’,‘It is decidedly so’,‘Without a doubt.’,‘Yes definitely.’,‘You may rely on it.’,‘As I see it, yes’

,‘Most likely’,‘Outlook good’,‘Yes’,‘Signs point to yes’,‘Reply hazy, try again.’,‘Ask again later.’,‘Better not tell you now’,‘Cannot predict now.’,‘Concentrat­e and ask again.’,‘Do not count on it.’,‘My reply is no.’,‘My sources say no.’,‘Outlook not so good.’,‘Very doubtful.‘]) answer = secrets.choice(range(0,myarray.size)) print (myarray[answer]) You can also download this script from https://github. com/nate-drake/arrayexamp­les/blob/master/magic8.py. This little five line gem creates a numpy array containing text values, namely the 20 possible answers given by users of the classic Magic 8 Ball toy. Notice that you can use myarray. size to determine the overall length of a numpy array instead of the more cumbersome len .

“Reply hazy, try again”

Aside from using text values and a more efficient type of array, the basic premise of this script is exactly the same as the previous ones you created in that it will print values based upon a random index. The standard Magic 8 ball contains 10 positive answers, five negative and five non-commital. If you want to make it a little fairer by adding another negative answer use the numpy.append function for instance: np.append(myarray,’No’)

If you do this using IDLE, the program will automatica­lly regurgitat­e a new list of all the array elements, including the one you just added.

In the case of this script, elements are chosen randomly, so their order doesn’t matter. If however you do want to add a value in a specific position to a numpy array, use the numpy.

insert function, for instance: np.insert(myarray,3,’Absolutely!’) This will place the word ‘Absolutely!’ as the fourth element in the list (remember the index counts from zero).

2D or not 2D

While Numpy can be used to create one-dimensiona­l arrays, for example a list of values, it’s perfectly capable of creating a multidimen­sional table of values, too. This isn’t a hard concept to grasp; however, most of the online documentat­ion related to Numpy tries to explain this in as convoluted way as possible, which is why we’ll devote some time to a more reasonable explanatio­n here.

The simplest type of multidimen­sional array has two dimensions, which are known as axes. A good usage example would be creating a two-dimensiona­l array to store both X and Y coordinate­s on a graph and indeed Numpy is designed specifical­ly for storing complex scientific data like this.

An easier way to understand two-dimensiona­l arrays is as being akin to rows and columns on a spreadshee­t. For instance, if you had a deck of cards you could arrange them into an array of four rows (representi­ng clubs, diamonds, hearts and spades) and 13 columns representi­ng the cards for each suit. Each card in this two-dimensiona­l array would have a unique index (or tuple as it’s known for multi-dimensiona­l arrays). The overall tuple of a multidimen­sional array is known as its shape. In the example above this would be 4,13.

Start of by creating a new file named drawcard.py and paste the following text. This results in a simple script using a two-dimensiona­l array to draw at random from a deck of cards, as follows: import secrets import numpy as np # Suits follow the Bridge order: Clubs (0), Diamonds (1), Hearts (2), Spades (3). deck=np.array([['Ace’,2,3,4,5,6,7,8,9,10,‘Jack’,‘Queen’,‘King'],[ 'Ace’,2,3,4,5,6,7,8,9,10,‘Jack’,‘Queen’,‘King'],['Ace’,2,3,4,5,6,7, 8,9,10,‘Jack’,‘Queen’,‘King'],['Ace’,2,3,4,5,6,7,8,9,10,‘Jack’,‘Qu een’,‘King']]) randomsuit=secrets.choice(range(deck.shape[0])) suit = ['Clubs’, ‘Diamonds’, ‘Hearts’, ‘Spades'] randomcard=secrets.choice(range(deck.shape[1])) yourcard=deck[randomsuit,randomcard] print('Your card is the ' + yourcard + ' of ' + suit[randomsuit] + '.‘)

Visualise your array

If you’re using IDLE, after running this script, enter the command print(deck) to output the two-dimensiona­l numpy array as text. This arranges the 13 cards for each suit in four rows, allowing you to visualise the array. The variables deck.shape[0] and deck.shape[1] represent the number of elements along each dimension (4 and 13, respective­ly). These are used to randomly select both a suit such as clubs and then a card within said suit such as the Jack. Note that the Numpy array is happy to store both numerical elements such as 9 and string elements such as King.

The index (or tuple) for the suits is an integer value, so the list suit is used to marry this up to an actual name (clubs, diamonds and so on). This isn’t necessary for the array to function, but enables the program to output the suit name in a meaningful way.

Any card in this array deck can be located using the format deck[X,Y] . This can be put to good use with the variable yourcard, which allocates a chosen card in the deck based on random values. You can also use this to display a specific card − for example, print(deck[2,11]) . If you want to change values to represent their points value for Blackjack for instance, simply declare the variable, such as deck[2,11]=10 .

Shattered dimensions

As this tutorial is designed to give you a basic introducti­on to arrays, there’s very little to go wrong. Raspberry Pi users who want to run the sample scripts may encounter some difficulti­es as the ‘secrets’ module used to generate random numbers only works with Python 3.6.

If you’re comfortabl­e with compiling software, you can download the latest stable version of Python from www.python.org/ftp/python (currently 3.6.4) and install it via the Pi Terminal. Use the command $ make altinstall to keep the existing version of Python. Alternativ­ely, rework the scripts yourself to use numpy’s own (less) random number generator instead of the secrets module ( https://docs. scipy.org/doc/numpy/reference/routines.random.html).

Needless to say, Numpy is capable of storing much more than dice rolls and shuffling cards. If you want to store and manipulate other data types in an array, take some time to read through the Numpy manual ( https://docs.scipy.org/ doc/numpy/). This contains details on more advanced ways of managing data such as byte ordering and subclassin­g, which haven’t been covered here. By default arrays are accessed as read only during runtime so changes you make are not saved from one session to the next. If you want to store an array in a file use numpy.save (there are more details at https://docs.scipy.org/doc/numpy/ reference/generated/numpy.save.html).

 ??  ??
 ??  ?? Arrays can store data related to ray tracing, a rendering technique for generating realistic images by tracing the path of light as pixels. All these objects are computer generated.
Arrays can store data related to ray tracing, a rendering technique for generating realistic images by tracing the path of light as pixels. All these objects are computer generated.
 ??  ??
 ??  ?? Use numpy.insert to place an element at a specific position in your array. If you simply want to add a value to the end, use numpy.append.
Use numpy.insert to place an element at a specific position in your array. If you simply want to add a value to the end, use numpy.append.
 ??  ?? Here the array deck has two axes. Although [2,11] and [3,11] both contain the string Queen, the card suits are distinguis­hable due to their positions within the array.
Here the array deck has two axes. Although [2,11] and [3,11] both contain the string Queen, the card suits are distinguis­hable due to their positions within the array.
 ??  ?? You can use the Thonny IDE with Python 3.6 in Raspbian. Once you’ve installed the new version of Python, go to Tools>Options> Interprete­r and select it from the drop-down menu.
You can use the Thonny IDE with Python 3.6 in Raspbian. Once you’ve installed the new version of Python, go to Tools>Options> Interprete­r and select it from the drop-down menu.

Newspapers in English

Newspapers from Australia