Hello World! [‘hip’, ‘hip’] Arrays

0
427

By Jeff Kazmierski, Copy Editor

We’re back with another installment of Hello World! and this week we’re discussing arrays. Hopefully this stuff is starting to make more sense to you, because in the next few weeks we’re going to look at some slightly more advanced topics.

We looked at arrays a little last week, in the context of strings (remember, a string is a collection of characters), and even mentioned string indexes and parsing. This week, we’re going to go into more detail. Buckle up, folks; stuff’s about to get real.

By now you should have noticed that variables in Python are powerful and flexible, but kind of limited. They can hold only one value at a time, so if you need to store several different data points, you need to create a bunch of variables to do it. For example, suppose you need to find the average of 10 numbers. Using normal variables, you’d have to initialize 10 different names:

# average.py    

a = int(input(“Enter value #1:”))    

b = int(input(“Enter value #2:”))    

j = int(input(“Enter value #10:))    

k = (a+b+c+d+…+j)/10

print(k)

Or do you?

Welcome to the wonderful world of arrays—a deceptively simple, yet powerful data construct that allows you to store multiple data points of a variety of types, all within a single named variable.

Before we begin, we’ll need a short explanation of what arrays are and how they work.

Arrays are a special type of variable that holds multiple values of related data instead of just one. Python uses three types of array, called lists, dictionaries and tuples. We’ll deal with each of them in the next few lessons, but this week is all about lists.

Time to do some code. Fire up your IDLE emulator and enter this at the command line:

>>> alist = []

That tells Python to set aside a block of memory to store some data. We don’t know what type or how much memory yet, but we’ll get to that. In Python, unlike Java, C or other compiled languages, arrays are dynamic. That means their total size in memory, and the number of items they contain, can change depending on your needs at the time.  Lists are mutable, which means you can add, remove, reorder or alter the objects stored there whenever you want. In Java and C you have to initialize your array to a specific type and size. Not so in Python.

The best way to illustrate this is by example. Now that we’ve created an empty list, we need to fill it with some stuff:

>>> for a in range(10):

    alist.append(a)

>>> alist

[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

>>>

We’ve just taken our empty array and filled it with ten integer values. We could just as easily have filled it with letters:

>>> alist = [letter for letter in “spam”]

>>> alist    

[ ‘s’, ‘p’, ‘a’, ‘m’ ]

Or the same item, repeated:

>>> knights     = [‘Ni’] * 4    

>>> knights    

[‘Ni’, ‘Ni’, ‘Ni’,     ‘Ni’]

Or words:

>>> list2 = [‘spam’, ‘eggs’, ‘sausage’, ‘spam’]

So if we iterate through list2:

>>> for a in     range(len(list2)):    

print(list2[a])

spam    

eggs    

sausage    

spam    

>>>

List items don’t have to be all the same type, either:

>>> alist.append(1)

[ ‘s’, ‘p’, ‘a’, ‘m’, 1 ]

Though in practice it’s best to keep your list data consistent to avoid confusion.  

Items in a list can be accessed by index, the same way as letters in a string.

>>> list2[1]    

eggs

Let’s go back to our first example. Instead of using ten different variables to store all the data points, we can use a list to do the same thing. Open up an editor window:

# list.py    

grades = []    

sum = 0    

for a in range(10):

    number =     int(input(“Enter grade     “+str(a+1)+”:”))

    grades.    append(number)

    sum = sum+

number    

print(grades)    

print(“The     sum is “,sum)    

print(“The average is “,sum/10)

Isn’t that much easier? Save it as “list.py” and run it.

Lists can even be two- or even three-dimensional:

>>> matrix = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ]

A list like that one has two indexes, one for the row and one for the column. If you visualize it like a spreadsheet it looks like this:

>>> matrix     = [ [0, 1, 2],    

[3, 4, 5],    

[6, 7, 8] ]

It’s basically a list of lists.  To keep things simple (or at least less confusing) I won’t go into three-dimensional lists at the moment.

Lists are referenced in what’s called “row-major” fashion, meaning the indexes are called by row, then column.  Remember, the indexes start at 0:

>>> matrix[0][1]    

1

>>> matrix[2][0]    

3

>>> matrix[1][1]    

4

Remember that; we’ll come back to it in a few more lessons when we write a short Tic-Tac-Toe program.

Lists are powerful and easy tools to use, once you get used to them. Learning how to use them will vastly increase your programming knowledge and skill and put you well on the way to becoming a true programmer.

For a little extra challenge this week, try writing a program that takes input of any type from the user, adds it to a list, then prints it out. Good luck, and good coding!

Arrays

Lists – A list is a mutable (changeable), ordered array of object references, accessed by index. Lists are initialized using square brackets ([]).

We’ll deal with each of them over the next few weeks, but this week we’ll concentrate on lists.

Dictionaries – Dictionaries are mutable tables of object references, accessed by key. A dictionary is initialized with curly braces ({}), and consists of pairs of values bound in parentheses like this: ( key:value ). You can access a dictionary entry by either key or value.

Tuples – These are ordered pairs of objects, like points in a Cartesian coordinate system ( (3, 2), (4, 3) ). The individual pairs are ordered as a single immutable (unchangeable) object.

List Functions

alist.append(x) – adds an item to the end of a list.

alist.sort() – puts the items in a list in order (alphabetical, numerical, etc).

alist.reverse() – sorts the list in reverse order.

alist.count(x) – returns the number of occurrences of object x in the list.

alist.insert(index, x) – inserts object x at the position indicated by index.

alist.remove(x) – deletes the first occurrence of object x from the list.

alist.pop(x) – removes and prints the first occurrence of item x.

alist.extend([x, y, z…]) – appends items in a list to the end of the current list.

Comments

comments