Sunday, March 2, 2014

Defining Dictionary Definitions

Python has another very useful data type that I have been putting off mentioning, a dictionary. I haven’t been putting it off because it is esoteric or un-useful. On the contrary it is very useful for programming. I have been putting it off because it is a bit more complex than the more fundamental data types and it is important to understand the fundamental types before dealing with dictionaries. However, I think we are ready for them now.

Python dictionary objects are somewhat similar to real-world dictionaries. They contain, what are known as “key:value pairs”. You can think of this in terms of a real dictionary. The “key” is the word you want to look up, the “value” is the definition of the key. There are several ways to create dictionaries so I’m going to dive in and we’ll learn as we go. We’ll start by creating a blank dictionary:

d = { }

image

Curly braces generally (but not always) denote dictionaries. When creating a dictionary with entries in it the entries should be entered as key : value pairs. Generally speaking, the key is a usually a string, though it doesn’t have to be. The value can be any type of python object or function. Let’s create a dictionary that tells us about our friend bob. We’ll include his age, height, job, and hobbies.

bob = { ‘age’ : 33, ‘height’ : ‘’’6’ 0” ‘’’, ‘job’: ‘Designer’, ‘hobbies’:[‘playing guitar ’] }

image

Now I have all of the information about Bob in one python dictionary. I can access the data like so:

<dictionary name>[<key>]

In this case something like bob[‘age’]…

image

Notice that the entries are different types of objects. Dictionaries can be collections of many types of data.

image

It’s important to note that dictionaries are “unordered”. We can see this by using a built-in dictionary method called keys( ). The keys( ) method returns a list of all of the keys in our dictionary.

image

Notice that the keys are not returned in the order in which we created them. This is because the data is stored without any ordering information.

Each value object in the dictionary can be manipulated using standard methods. For instance, if we wanted to add a hobby to bob’s list of hobbies we could do so using the list’s append( ) method.

image

But what if we wanted to include additional information that wasn’t available when we created the dictionary? Not to fear, it is as simple as adding a key value pair. Let’s add bob’s birthday:

image

You can see it is almost as simple as creating a new variable, only we create the variable within the dictionary. Now I’m going to create a new dictionary for another friend.

image

Now, I’m really going to blow your mind and make a blank dictionary called friends and add bob and bill to it.

image

Now we’re really getting some complex data storage. Now if I want to access information on either friend I can do so using multiple keys:

image

Because the dictionary’s keys( ) method returns a list of keys, I can use it to loop through my friends and access information using a for loop.

for x in friends.keys():
    print x
    print “Birthday:”, friends[x][‘bday’]

image

Dictionaries have several built-in methods. I just want to mention the more common and useful ones before we wrap this up. We have already used the keys( ) method which returns a list of the dictionary’s keys. There is a similar method for returning a list of all of the values in a dictionary, creatively named values( ). It is used exactly the same way that keys( ) method is used.

Finally, there is the has_key( ) method. This method, as you might expect, tests whether a dictionary has a particular key and returns True or False. This method can be very useful because calling a dictionary with a non-existent key will result in an error. This function can be implemented to avoid those errors.

image

Though our example seems simple, dictionaries are incredibly powerful programming tools. Hopefully, this example starts to bring sites like facebook or twitter to mind. Imagine you were creating a social networking website in which each of your users input information about themselves. Then those users started linking together. You might consider using data structures like dictionaries to keep track of all that information.  Next time we will expand that power, as well as our own programming power by learning about how we can read and write files from our programs.

Saturday, February 22, 2014

Conjunction Junction, what's your function?

Functions.... Functions are kind of like little miniature programs, that you can run over and over from within a program. We have already experienced some functions in previous posts. Functions are always characterized by their parentheses ( ). So len( ) is a function, raw_input( ) is a function, sorted( ) is a function, dir( ) is a function. If you play video games, jumping, or attacking, or moving would all be different types of functions. Usually, functions have a definition, some arguments, and a return statement. The definition is the only item that is necessary for a function to work, though you should also always add a return statement even though it is not required. So, to start, we'll make a really simple function.
def sayHello( ):
    print "Hello, nice to meet you."
The first thing you should notice when you complete the code is that nothing happens. The reason is that we aren't writing the function to be run immediately, we are "defining" a function to be stored in memory that we can run whenever we need it. In order to run it simply type sayHello( ). The first line is where we tell the interpreter that we are defining the function, by saying
def  <function name>( ):
Def is short for define, function name can be whatever you want it to be, but it should describe what the function does. Everything that comes after the definition statement is the code that will be run when the function is called. Now we'll create a function that takes an argument.

Let's recreate the len( ) function. I'll demonstrate the code and then we'll go through it.
def length( item ):
    length = 0
    for x in item:
        length += 1
    return length
That should do it, remember to keep your indent levels consistent.  Arguments are the term for anything that you "give" to the function in order for it to run. In our case we are giving a sequence style object (string, list, or tuple) to the function and it is measuring the number of elements in the sequence. It is important to note that the object the function uses in its code block is not the same as the object that is given as an argument. That is a confusing statement so I'll explain a bit more using our length( ) function.

Let's say we have a string object, myString, with a value of "abc". Then we call our function with length( myString ). The interpreter returns a value of 3. 
What actually happens internally is the interpreter sees that we are calling a function called length with an argument called myString. The interpreter then finds the length function in memory and sees that it accepts an argument called item. So it takes the myString object and copies it to a new object called item. Then it runs the code on the item object leaving the myString object untouched. This isn't so important in this example, but for our next example we'll write a function where it does matter.

Let's try to recreate the reverse method that is built in to list objects.
def reverse( myList ):
    newList = [ ]
    total = len(myList) - 1
    while total >= 0:
        newList.append(myList[total])
        total -= 1
    myList = newList
    return myList
To test, let's create a list object called x and set it equal to [9,8,7,6,5,4,3,2,1]. Then run the reverse function on it. Now type print x.
So you see that even though the function returns the same argument that it receives it does not affect the original object. This is because as soon as the function begins running it creates a copy of the argument, rather than performing any modifications to the argument itself. However, you can set the argument object to the return value of the function. That's also confusing... Let me give an example
x = reverse(x)
Doing this will set the x object equal to the return value of the reverse( ) function.
You can also write functions that take more than one argument by simply separating the arguments in the parenthesis with a comma. You can add as many arguments as you need:
def add(a, b):
    return a + b
That brings us to return statements. Return statements do two very important things: they dictate what the function will return to the interpreter and they terminate the function. So when we run our reverse( ) function it returns myList, which is a list object, so we know that anytime we run the function, we will get a list object in return. However, you can have multiple return statements in a function, and each return statement can return a different type of object or even no object at all. To demonstrate I'll quickly rewrite our sayHello( ) function.
def sayHello( ):
    print "Hello, nice to meet you."
    return
Adding the blank return statement is not necessary but it is also not detrimental, and it let's anyone who is reading my code immediately see that the function only does one thing and then terminates. It is just good practice to include return statements, even if the function doesn't actually return anything.

A function that might have multiple return statements would be something like a function that tests whether a number is even or not.
def isEven(n):
    if n % 2 == 0:
        return True
    else:
        return False
Another good practice is to check your arguments in your function to avoid errors, return statements can be useful in this regard as well. For instance, our length( ) function is supposed to accept a sequence style object as an argument. If you call the function with an integer as the argument, the function will error out. But the error might not make it obvious what has gone wrong. Let's redefine the length( ) function to check the input before running any code. If the input is not correct, we will tell the user what the problem is and terminate the function to avoid errors.
def length( item ):
    if type(item) == str or type(item) == tuple or type(item) == list:
        length = 0
        for x in item:
            length += 1
        return length
    else:
        print "This function requires a string, tuple, or list, as an argument."
        return

Now the function will only run if it receives the input it is looking for. This is also good practice when writing code. The more you minimize errors, the better. If errors do occur, then it is nice to have an explicit explanation of what went wrong so you can easily go back and fix the problem.

Two mores thing I'd like to go over before wrapping this up: keyword arguments and splat arguments. Keyword arguments are "optional" arguments you can supply to a function. When I say optional, I mean the function user doesn't have to supply the argument, because it has a default value. However the argument is still necessary for the function to work properly. I'll give an example by writing a function that takes a sentence and returns a word from the sentence.
def getWord(sentence, index = 1):
    wordCount = 0
    letterCount = 0
    start = 0
    for letter in sentence:
        letterCount += 1
        if letter == " ":
            wordCount += 1
            if wordCount == index:
                return sentence[start:letterCount - 1]
            else:
                start = letterCount
    return sentence[start:]

Now, when we run the function with only a sentence argument, it returns the first word because the index keyword argument that we specified in the definition line has already been set to a value of 1. If we want to get a specific word, we can reset the index keyword argument to whatever word we want.

Finally, splat arguments. Splat arguments are what you use when writing a function that takes an indeterminate number of arguments. For instance, if you are writing a function that adds some numbers together, but you don't know how many numbers there will be use a splat argument in your definition like so:
def addNumbers(*args):
    sum = 0
    for n in args:
        sum += n
    return sum

Note that the splat argument has a '*' in the definition line, but is used like a standard sequence object in the code block. The interpreter takes the splat argument and creates a tuple of all of the arguments supplied to the function. So when dealing with the splat argument in the function's code block you can treat it just like any other tuple.

There is a lot more to say about functions, but this should be a pretty good introduction to writing your own functions. We've covered all the basics of function writing (and then some). Not so bad eh? Functions are one of the most important and often used concepts in programming and we will be dealing with them a LOT, so if you don't get it all now, don't worry, we'll cover functions again and again as we go forward.

Friday, February 14, 2014

Hustle and Flow… control

Common operators

Now that we’ve covered a bit of the basics, I wanted to give a list of some of the basic operators and what they do, both for review and for future reference. Some of these you have seen already. Many of them will be new.

Arithmetic Operators

Meaning / Effect

+

addition

-

subtraction

*

multiplication

/

division

%

modulo:
This performs an integer division and returns the remainder instead of the quotient. So 10 % 3 returns 1 because 3 goes into 10 three times with a remainder of 1.

**

exponent:
2 ** 3 = 8

//

Floor division:
Returns a float value rounded down to the nearest integer.
9.0 // 2.0 = 4.0

+=

Adds a value to a variable.
x += 1 is equal to x = x + 1

-=

Subtracts a value from a variable.
x -= 1 is equal to x = x 1 1

*=

Multiplies a variable by a value.
x *= 2 is equal to x = x * 2

/=

Divides a variable by a value.
x /= 2 is equal to x = x / 2

There is another type of object called a boolean. A boolean is simply a object that contains a value of True or False. Booleans are very important for writing intelligent programs. Example: x = True. All of the below comparison operators return boolean objects, meaning True or False.

Comparison Operators

Meaning / Effect

==

Compares two objects,
If they are equal it returns True otherwise it returns False

!=

Compares two objects,
If they are not equal returns True otherwise it returns False

>=

Compares two objects,
If left side object is greater than or equal to the right side object returns True, otherwise returns False

<=

Compares two objects,
If left side object is less than or equal to the right side object returns True, otherwise returns False

>

Compares two objects,
If left side object is greater than the right side object returns True, otherwise returns False

<

Compares two objects,
If left side object is less than the right side object returns True, otherwise returns False

 

Sequence / Collection Operators

Meaning / Effect

in

Tests if an object is in a sequence object. Returns True if the object is in the list, otherwise returns False.
Example:
’x’ in [‘x’, ‘y’, ‘z’] returns True
’x’ in [1, 2, 3] returns False
’x’ in ‘ham’ returns False

 

Logical Operators

Meaning / Effect

and

Usage: x and y
If x = True and y = True returns True
If x or y = False returns False
If x and y = False returns False

or

Usage: x or y
If x = True and y = True returns True
If x or y = True returns True
If x and y = False returns False

not

Reverses the outcome of True/False evaluation
’x’ in ‘ham’ returns False
’x’ not in ‘ham’ returns True

If / else statements

Now that we have all of these lovely comparison operators let’s start putting them to good use. The if / else statement allows us to make decisions within our programs intelligently. Let’s dive in, beginning with the ‘if’ statement. It works like this:

if <condition is True>:
    <do something>

Notice that the ‘do something’ portion of the statement is indented just like in the loop statements we covered in the previous post. So, let’s do something with it, start by making an integer variable and set it equal to 5:

x = 5
if x > 0:
    print “x is a positive number.”

image

Big deal right? We already knew that five is a positive number. But what if we had a range of numbers and we wanted to know which ones are positive and which are negative? Perhaps we can combine the if statement with the for loop we covered in the last post…

numbers = (5, 15, –2, –9, 5, 13, –2, 7)
for number in numbers:
    if number > 0:
        print number,

image

You can see that combining the simple tools we have learned so far will allow us to write very complex and powerful programs. Let’s take the same tuple of numbers from the last example and write a program that tells us if a number is odd or even. In this instance we are going to need to do something if the number is even and something else if the number is not even. And, as you might have been able to tell the the name, we are going to use the “else” statement. The else statement is a pretty simple concept, it defines what needs to be done if the ‘if’ condition isn’t true. In the last example when ‘if’ was true, we did something. If it wasn’t true, we did nothing. Now with the else statement we can cover all our bases.

for number in numbers:
    if number % 2 == 0:
        print number, “is even.”
    else:
        print number, “is odd.”

image

Now this is starting to look like programming. Let’s walk through it line by line.

Line 1: “For each number in the tuple called numbers:

Line 2: The second line uses the modulo mentioned earlier in this post. It provides us with the remainder left over after a number has been divided. In this case we are saying: “If the number from the list has a remainder of zero when we divide it by 2 then…”

Line 3: “print the number, followed by “is even”. Because a number that can be evenly divided by 2 is always even.

Line 4: “Otherwise, if the number cannot be evenly divided by two…”

Line 5: “print the number, followed by “is odd.” Because any number that is not even is odd.

Pretty simple huh? But it is significant. This is the first logically driven program we have written so far. Not terribly exciting, but consider the fact that you can input any number in the universe into this program and it will tell you whether it is odd or even, and it only took 5 lines of code. You can logically cover all numbers from -infinity to infinity with just these simple lines. Imagine what you can do with a few more.

There’s one more statement that can be used in the if/else statement. It’s called ‘elif’ (short for else if). It is pretty simple also. An ‘elif’ simply adds another testing condition into the statement. An ‘elif’ gets tested for after the if condition is found to be false. So, if we wanted to not only find if a number is odd or even, but also wanted to know if it was divisible by 5. We could modify our tests like so using some ‘elif’ statements.

for number in numbers:
    if number % 2 == 0 and number % 5 == 0:
        print number, “is even and a multiple of 5.”
    elif number % 2 == 0:
        print number, “is even”
    elif number %5 == 0:
        print number, “is odd and a multiple of 5.”
    else:
        print number, “is odd.”

image

Now, there are many different ways to write the same code and this isn’t the most efficient, BUT I don’t want to confuse you too much at this point so I am trying to keep it simple. I’ll walk you through the logic of the if/else statements I used so you can see why I’m doing things in this order. The first thing I test for is if the number is even AND  (notice the logical operator I used, see above tables for details) is a multiple of 5. If that test comes back true then I print the response. If it’s not true, then I test if it is even, without worrying about the multiple of 5. If both of those aren’t true then I know that the number is odd. So all I need to test for now is if it can be divided by 5. If it can then it is an odd multiple of 5, if it can’t then it is just an odd number.

We’ve got a lot of the pieces we need for starting to really start writing some programs. There is still plenty more to learn but with the knowledge you’ve got so far you are well on your way to writing some simple programs. Next time we’ll cover writing functions. Only a few more lessons and you’ll be looking for your first entry level python programming job. Huzzah!!! XD


BONUS
If you are interested in a more efficient solution to the above problem, here you go.

for number in numbers:
    if number % 2 == 0:
        if number % 5 == 0:
            print number, “is even and a multiple of 5.”
        else:
            print number, “is even.”
    elif number % 5 == 0:
        print number, “is odd and a multiple of 5.”
    else:
        print number, “is odd.”

image

As you can see it is possible to have if statements inside of if statements. This is called “nesting” but we’ll talk about that in a later lesson. The reason this implementation is more efficient is because it requires the computer to do fewer tests on the number. In order to solve the problem that we set out to solve we need to know two pieces of information, is it even and is it a multiple of 5.

In the first set of code we tested number divided by 2 and then 5. Then we tested dividing by 2 again. Then we tested 5 again. If we follow the code we see that the minimum number of tests a number will go through is 2 (which is the minimum required we need to solve the problem),  but the maximum number of tests is 4 (in the case of an odd number). In this new implementation the maximum number of tests that can happen to a number is 2, the same as the minimum, which means this code is now “optimized”. There are still more ways to optimize it and make it faster but it gets into advanced computer sciencey subjects I’d prefer to avoid for the time being. All things in time…

Sunday, February 9, 2014

Compute Loops

Now that we know how a few collection/sequence style objects work we can dive into some more powerful ways to utilize them through looping.

Looping is a relatively simple concept. It provides a means of telling the program to run the same bit of code over and over a number of times. This is useful because it prevents the programmer from having to rewrite the same code over and over. There a few different types of loops. The first one we are going to look at is the “while” loop.

The ‘while’ loop

The while loop is pretty simple. It tells the computer that while a certain condition is true, keep doing a certain type of code. The classic example of the while loop involves printing a series of numbers to the console using three lines of code. It looks like this:

a = 0
while a < 10:
    print a
    a = a + 1

image

Notice, at the end of the “while” line I added a colon “:”. The colon lets the interpreter know that the indented code on the following lines is what should be run until the “while” condition is met. In this case, as you can probably guess, we are instructing the computer to to print the variable a as long as it has a value that is less than ten. One thing that can be annoying about Python is the indentation. Your indentations can be spaces or tabs but not both. Meaning if your first indentation is done with spaces, all of the following indentations must also be spaces. If you use tabs, then you have to continue using tabs. The number of spaces doesn’t matter, so long as it is consistent. The general rule of thumb is 4 spaces for each indentation. In Notepad++ there is an option in the “Settings > Preferences” dialog for “tab settings” you can set it to replace your tabs with spaces. I would recommend using that option if you use Notepad++.

image

While loops can be very useful, but there is also a danger in using them. Imagine what might happen if we didn’t include the last line in the code above, a = a + 1. Without that line, a would always be equal to zero, meaning that the “while” condition would never be met and the computer would continue printing a indefinitely until the end of time. (If this happens press “ctrl + c” to terminate your program.) This is known as an “infinite loop” and it is to be avoided. As a safety measure, when writing a while loop, it is a good idea to put the the code in that will complete the loop first and then insert the code that needs to run during the loop above it. There have been many times that I have written while loops that have some complicated code to run and by the time I finished writing the code I forgot to add the line that would fulfill the while condition.

Here is an example of a while loop that prints all of the numbers in the fibonacci sequence up to 1000.

a = 0
b = 1
while b < 1000:
    print b
    x = a
    a = b
    b = x + b

image

Try running the code again, but add a comma after the “print b” line.

image

The ‘for’ loop

The ‘for’ loop is a wonderful little tool for accessing all of the elements in a sequence/collection style object. That means that for loops can be used with strings, lists, and tuples (as well as a few other objects). It works like this:

for <variable> in <object>:
    do something

Let’s learn through practice. Make a string object called myString and set it equal to some word. Then use a for loop to print out each letter individually like so:

for letter in myString:
    print letter

image

The ‘letter’ in the above example doesn’t have to be ‘letter’ it could be any variable name. The word that comes after ‘for’ is a variable name. The for loop then loops through the sequence object and assigns each item in the object to the variable name specified. This looping is known as “iterating” in programmer jargon and so the act of looping is known as “iteration”. So, if you are describing the above program you can say that “I am iterating through my string and printing out each character.” In the above example we are telling the interpreter: for each character in myString, assign the character to a variable called letter, then do whatever code is below.

So in my example myString = “cow” and when I ran the code it printed the letters c o w. I could also have told it to print myString and it would have printed “cow” three times. Why? Because the for loop performs some code for each item in the object. “cow” has three characters so for each character it will run the code “print myString”.

image

So you see, you don’t only have to use for loops to do things with the items in a sequence or collection object. For instance, if there wasn’t a len() function available to us, how might we write one using a for loop? Observe:

length = 0
for x in myString:
    length = length + 1

print length

image

Here we ignore the value of x, we simply add 1 to the value of our length integer object each time we encounter an item in the myString object. Notice that when I added the print length line I didn’t add any indentation. This lets the interpreter know that it shouldn’t run the print line until it is finished with the for loop. So the interpreter knows that the any code that is indented under the for loop should be run in the loop, when it finds a line that is not indented it will not run it until the for loop is complete. See what happens when I don’t indent the print statement.

image

Loops can also be used with lists and tuples in the same way that they are used above. For example:

myList = [‘camera’, ‘steve’, 4, ‘cheesesteak’]
myTuple = (‘flippy’, 912, 0.0074, myList, 99, 42, ‘bilbo’)
for item in myTuple:
    print type(item)

image

That’s it for loops for now. Next post we will discuss the if / else statement and boolean objects and I’ll probably throw in some comparison operators…anyway, more on that next time.

Saturday, February 1, 2014

He’s makin’ a list, he’s checkin’ it recursively

We’ve dealt with strings, we’ve received the t-shirt. Now it’s time to look at another collection style object, the “list”. Python lists are wonderful little creatures that allow us to organize and manipulate data quickly and easily. We have already encountered some lists. When we ran the sorted() function on our string object in the mad libs post, the object that was returned was a list. If you recall, a “string” is a collection of characters. A list, on the other hand is a collection of anything. You can create lists of numbers, lists of strings, lists of custom objects, even lists of lists. You can also make lists of multiple types of objects. So you could have a list with integers, floating point numbers, and strings, etc. Lists also come with lots of built in methods that make using them fast and easy. 

Let’s begin by creating a list. List creation is similar to string creation, except that instead of enclosing your list items in quotes, you use the square brackets ‘[‘ and ‘]’ to denote the start and end of your list. Each item you want to put into your list should be separated by commas. Open your interpreter and type:
myList = [‘a’, ‘b’, ‘c’, ‘dog’]
Lists are easy to spot because they will always be enclosed in square brackets. Accessing items in lists uses the same indexing system that strings use. The first item has an index of 0, the second item’s index is 1, etc. 

Note that if you check the type of myList using the type() function, it will return 'list'. However, if you check the type of myList[<index>] it will return the type of the item in the list, in our case, a 'string'. This is because the list object is acting as a container for the objects inside. So the list is and object, and the items in the list are also objects. Each object in the list will retain its original properties. Scary and a little confusing, but powerful. See below:


One of the cool things about lists is we can change them without needing to redefine them. For instance, if we create a list and then later on need to add or remove an item we can do that without having to create a new list. There are several ways to add and remove items from lists.

Common methods for adding or removing objects to/from lists
Method Description
myList.append(<item>)
The append() method will add an item on to the end of a list. This is a useful function when starting with a blank list and adding items to it.
 
myList.insert(<index>, <item>) The insert() method allows you to put an item into your list in whatever location you choose.
myList.remove(<item>)
The remove() method will remove the specified item from the list. If there is more than one occurrence of the item in your list, the remove() method will remove the first item, and leave the rest.
myList.pop()
myList.pop(<index>)
The pop() method will remove the the last item in your list. You can also give an index number to the pop method and it will remove the item at the index number. If no index is given then it will remove the last item in the list.

Like I said, there are lots of cool ways to access and manipulate lists; LOTS of ways. I’m going to cover some of the more common methods in this post, and probably mention some of the more obscure methods in later posts. Now that we know how to add and remove items, let’s look at some methods that allow us to play with the data in our lists. For the following examples I am going to define a new object.
testList = [‘hogwarts’, ‘salmon’, ‘alpaca’, 4, ‘cheese’, 2, ‘superman’, ‘cheese’]
Common methods for adding or removing objects to/from lists
Method Description
testList.reverse() The reverse() method reverses the order of the list.
testList.count(<item>) The count() method counts the number of times the specified <item> occurs in the list.
testList.sort() The sort() method orders the items in the list, numerically and/or alphabetically.
testList.index(<item>)
The index() method returns the index number for the specified <item>. If there is more than one occurrence of the <item>, then index() will return the index number of the first occurrence.

 

Finally, there are a few more built in python functions that can be used with lists, some of them you’ve seen before when dealing with strings. (I told you there was lots of stuff you can do with them.)
Built-in Python Functions that can be used with lists
Function Description
len(<list>) This function works just like it did with strings. The value returned will be an integer that specifies the number of items in the list.
max(<list>)
The max() function will return the item in the list with the maximum value. In the case of numbers, the highest number will be returned; for strings, the highest alphabetically ordered string will be returned.
min(<list>) Like the max() function, min() will return the item with the lowest alpha or numeric value.
sum(<list>) The sum() function only works with numeric lists. It adds all of the items in the list together and returns the sum. If there are non-numeric items in the list, sum() will error.

Tuples

I can’t talk about lists without mentioning it’s less popular and underappreciated kid brother, the “tuple”. Tuples are similar to lists in many ways, but different in one very key way. Tuples are unchangeable. Unlike his big, popular, handsome brother, the tuple has no methods for adding or removing elements. Once the tuple is created, he cannot change. The term programmers user for this is “immutable”. Tuples are immutable objects. Immutable is just a fancy and unfriendly way of saying unchangeable. Programming, like most other fields, likes to use jargon that other “outsiders” won’t easily understand.

Tuples and lists look very similar, but you can always spot a tuple because, instead of being enclosed in square brackets ‘[ ]’, the tuple is enclosed in parentheses ‘( )’. Tuples can be created the same way as lists, just enclose the items in ‘( )’ instead of ‘[ ]’.
myList = [‘cheese’, ‘eggs’, “welch’s grape”]
myTuple = (‘cheese’, ‘eggs’, “welch’s grape”)
The purpose of the tuple is often difficult to understand for new programmers, especially python programmers. This is because Python, unlike the ‘C’ programming languages, manages memory for you. The reason the tuple exists is that it uses less memory than a list, and it can be accessed faster. So, tuples should be used when you have a constant list of items that won’t require any ‘in-program’ changes. For example, if you want to write a program that sorts items into pre-defined categories, the list of categories should be put into a tuple because the categories will be:
  • Defined before hand
  • Accessed often
  • Not changed during the program’s execution.
So, don’t dismiss tuples, in many situations they can perform better than the bulkier list object. Plus, it’s a fun word to say... tuple. If you start talking about immutable tuples, other programmers will perk up and know that you are a member of the club.

There is a lot more that can (and will) be said about lists, but this should be a good enough primer to get you familiar with their operation. I will probably do a follow up post to this one that has practical applications for the functions that I have mentioned in this post. After that we will discussing ways of comparing data and making decisions within our programs. Stay tuned.