Beginning Python: Data Types

of 10


As I said in the tutorial "How a Computer Looks At Your Program", computer programs consist of data and code. In order to make code able to be used for more than a single set of data, computer programs use variables, or containers for data. These containers are technically called data structures because they allow the data to be structured in different ways. Just like you would probably be disinclined from cooking pasta in a coffee cup or drinking tea from a vat, so Python offers a variety of containers for different kinds of data.

In Python, there are five basic data structures or types of variables: integers, strings, lists, tuples, and dictionaries. In the following pages, we will look at each in turn.

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6

of 10


An integer in Python, also known as a 'numeric literal', is simply a name used for a numeric value. For this reason, these values are commonly called integers even if they are assigned the value of a real number in the form of an integer and a decimal value. Any numeric value can be assigned to it at any time, overwriting the previous value.

To assign a value to an integer variable, one writes a statement after the following template:

 <numeric literal name> = <numeric literal value> 

Some examples are:

 x = 1500 
 pi = 3.14 
of 10

Strings - Part 1

A string literal, or string, holds any combination of letters and numbers you would like it to hold. Any number it holds, however, is not treated like a numerical value but is preserved as if it were a word.

One way to think about the difference between a number as a string and a number as a numeric literal is to consider a credit card. The credit card numbers themselves are an example of an integer value; you can add to them and subtract from their value. The credit card, however, preserves the numbers in a set format, complete with spaces. A string does the same thing. While you can multiply and divide the number of the credit card as an integer, you cannot break up the value by the way it is written. To do that you need a string. In this way, an integer represents a quantity, a string represents a quality.

of 10

Strings - Part 2

Because a string represents words and numbers in the format they are assigned, Python uses quotes to indicate their value. Trying to assign a string value without quotes looks like you are trying to assign the value of one string to another. If the string does not yet exist, Python will tell you so. To assign a value to a string, one uses the following template:

 <name of string> = '<value of string>' 

Examples of variable assignments are:

 gettysburg = "four score and seven years ago..."
 writ = 'habeas corpus'
 Catch22 = """no win situation"""
 postcode = '''91101-2509''' 

"Wait a minute!", I hear you say, "You said that Python uses quotes to offset string values. You used single quotes in the template and then used single, double and triple quotes in the examples. Which is right?" The fact of the matter is that Python allows all of them. You get to choose which you want to use. Python does not care. All Python asks is that you close the value with the same kind that you opened it (otherwise, Python will not know where you mean the quotes to be part of the value or to signify the end of the string). If you begin a value with double quotes, you must end it with double quotes. The following are therefore WRONG:

 name = 'Joanna Sebastian Bach" 
 body = "Sargasso See' 
 city = """Ed in burgh''' 
of 10

Strings - Part 3

"But what do I do if I need to use a single quote when I already started with a single quote? Won't Python get confused?" It certainly will. If you use single quotes around the value, double quotes in the value are fine. Similarly, if you use double quotes around the value, single quotes are allowed in the value itself. However, if the value contains the same mark as the one used around it, you must use escape that part of the value.

Escaping is a fancy way of saying that you break out of the norm. It happens within quotation-like arguments when one places a backslash in front of a character like: "\n". When certain characters are 'escaped' they take on a different meaning. So, while a single quote may indicate a string's value, an escaped single quote within that value means something else: an actual single quote! The same is true for double quotes.

For more escaping, see the page "Escape Sequences".

of 10

Accessing Variables

To access the value of a variable within the Python shell, simply type it.

 >>> x = 1500 
 >>> x 

Within a program, one can use the 'print' command.

 cat = 'dog' 
 print cat 

If the variable is a string, you can also access its parts. Each character of the string is indexed, starting with the first character at '0'. By accessing the string with an indexing operator, you can access only part of the string and leave the rest untouched. An example:

 cat = 'dog' 
 print cat[0] 
 print cat[1] 
 print cat[2] 
of 10

Working With Variables

Working with Integer Variables

As you might imagine, you can perform any mathematical operation you like on a numeric literal.

 d = 300 
 pi = 3.14159265 
 circumference = pi * d 
 r = d/2 
 c = 2 * pi * r 
For more operators, see the page "Python Operators".

Working with Strings

With a string, one concatenates instead of adding. One can concatenate strings or their values. The result is a string that shows no indication that the two parts were ever separate. So if you need a space between the parts, you must be sure to include it when the two strings are joined.

 a = 'big' 
 b = 'baboons' 
 phrase = a + b 
 full_phrase = b + " with " + a + " bahoochies" 
 print phrase 
 print full_phrase 
 baboons with big bahoochies 

If you want more than one letter but still less than the whole string, you can cull out a substring by using the slicing operator:

 >>> b = 'baboons' 
 >>> z = b[2:7] 
 >>> print z 

You can, of course, combine that substring with another string value and assign both to a single string literal.

 >>> b = 'baboons' 
 >>> word = 'ball' + b[3:7] 
 >>> print word 
of 10


Assigning Values to a List

A list is, as the name suggests, a series of values. In Python, these values are assigned by placing them within square braces and separating them by commas like this:

 <name of list> = [ <value>, <value>, <value> ] 
 girls = ['sugar', 'spice', 'everything nice'] 
 lotto = ['26', '12', '23'] 
 addends = [4, 34, 7] 
Note that 'addends' is comprised of integer variables while the others are comprised of strings, as the quotes suggest.

A list can contain any type of Python object -- even other lists.
 >>> lotto[2] = addends 
 >>> print lotto 
 ['26', '12', [4, 34, 7]] 

Accessing the Values of List

To access a part of a list, one uses the same kind of phrase as one used for a string literal:

 <name of list>[<index number>] 
A few examples:
 ingredient1 = girls[0] 
 print girls[1] 
 print 'brown ' + ingredient1 
 print girls[0] + " is not a " + girls[1] 
brown sugar
sugar is not a spice

Combining Lists

Lists can be concatenated in a way similar to strings by using the plus operator ('+'):

 primes = [1, 3, 5, 7] + [9, 11] 
 mishmash = girls + lotto + addends 
 print primes 
 print mishmash 
[1, 3, 5, 7, 9, 11]
['sugar', 'spice', 'everything nice', '26', '12', '23', 4, 34, 7]
of 10


In Python, a tuple may be defined as a finite, static list of literals (numeric or string). For our purposes, a tuple is very similar to a list in that it contains a sequence of items. It differs from a list in that it cannot be changed once it is created. One can index, slice and concatenate, but one cannot append or alter the values of the tuple after it has been initialized.

To initialize a tuple, one encloses the values in parentheses and separates them by commas.

 directions = ('north', 'south', 'east', 'west') 
 coordinates = (45, 34, 48, 32) 
 print directions[3] 
 print coordinates[1] 
of 10


Defining a Dictionary

Dictionary is the Python term for an associative array. An array is, like a list, a series of values in two dimensions. An associative array gives one a way of accessing the values by a key, a term associated with the value instead of an item's index number.

Initializing a dictionary, one offsets the keys and values in curly braces. Each key-value pair is separated from the others by a comma. For each pair, the key and value are separated by a colon. The key of each member is offset in quotes. A sample dictionary is as follows:

 my_dictionary = { "author" : "Andrew Melville", 
 "title" : "Moby Dick", 
 "year" : "1851", 
 "copies" : 5000000 

Accessing a Dictionary

One accesses a dictionary member by its key:

 >>> a = my_dictionary["author"]
 >>> print a 
 Andrew Melville 

To insert or modify a member, one simply assigns the value:

 >>> my_dictionary["publisher"] = 'Harper and Brothers' 
 >>> my_dictionary["author"] = 'Herman Melville' 
 >>> print my_dictionary 
 {'publisher': 'Harper and Brothers', 'title': 'Moby Dick', 'year': '1851', 'copies': 5000000, 'author': 'Herman Melville'} 

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6