INTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

CHAPTER 8. LISTS, DICTIONARIES, TUPLES

Variables allow us to store information that can be changed anytime. However, they store a single piece of information at a time: a value, a string, etc.

What if we need to store a list of information that will not change over time?

For example, the contact information of your family members, the names of the months of the year, or a phone book where you have multiple information ( the name of the contact and related phone numbers.

This is where Lists, Tuples, and Dictionaries come in. Let’s briefly discuss each so you know the difference, before using them in a code.

List

As the name implies, it is a list of values. The values in a list are counted from zero onwards (the first value is numbered zero, the second 1st, and so on). List lets values to be removed and added at will.

Tuples

They are similar to lists except their values cannot be modified. Once created, the values remain static for the rest of the program. Again, the values are numbered for reference, starting with zero.

Dictionaries

Like a normal dictionary, it allows you to create an index of words where each word has a unique definition. In Python, the word is called the ‘key’ whereas its definition is called its ‘value’. Like  a dictionary, none of the words/keys are numbered. The values in the dictionary can be created, removed, and modified.

Let’s start with the unchanging tuples.

USING TUPLES

Tuples are easy to create. Name your tuple and list the values that it will carry. Here’s a tuple for carrying the months of the year:

months = ('Jan', 'Feb, 'Mar', 'Apr', \ 'May',' Jun', 'Jul', 'Aug, 'Sept, 'Oct, \ 'Nov,'  ‘Dec’)

Syntactically, a tuple is a comma-separated sequence of values. The parenthesis and the space after the comma are simply a convention, and not necessary for creating a tuple. Furthermore, notice the ‘\’ at the end of each line? It carries the line to the next line, making big lines more readable.

Once created, Python creates a numbered index to organize the values in a tuple. Starting from zero, the values are indexed in the order you entered them in the tuple. The above tuple becomes:

Index

Value

0

January

1

Feb

2

Mar

3

Apr

4

May

5

Jun

6

Jul

7

Aug

8

Sep

9

Oct

10

Nov

11

Dec

So if you were to call the tuple ‘month’, you will use the index to call it:

>>>month [2]

Mar

Additionally, Python has a very powerful tuple assignment feature that allows us to assign value to variables on the left with values on the right. Hence, for the ‘months’ we have created earlier, we can further assign values to each of the value in the list:

>>>(research, submit outline, discussion, study, seminars, presentation, field trip, submit paper, panel discussion, final presentation, semester ends) = months

The only requirement is that the number of variables on the left must equal the number of elements declared in the tuple.

A simple way of looking at this assignment is to to think of it as tuple packing/unpacking. When packed, the values on the left are packed together:

>>> months = ('Jan', 'Feb, 'Mar', 'Apr', \ 'May',' Jun', 'Jul', 'Aug, 'Sept, 'Oct, \ 'Nov,'  ‘Dec’)

In tuple unpacking, the values on the right (the names of the months) are unpacked into variables/names/categories on the right:

>>> months = ('Jan', 'Feb, 'Mar', 'Apr', \ 'May',' Jun', 'Jul', 'Aug, 'Sept, 'Oct, \ 'Nov,'  ‘Dec’)

>>>(research, submit outline, discussion, study, seminars, presentation, field trip, submit paper, panel discussion, final presentation, semester ends) = months

>>> research

Jan

>>> seminars

May

>>> submit outline

Feb

Another powerful use of tuple is when you have to swap the values of two variables. Normally, you would have to use a temporary variable for swapping:

#Swap ‘b’ with ‘a’

temp = b

b = a

a = temp

A tuple resolves this in a single line:

(b, a) = (a, b)

Simple. The right hand side is a tuple of values while the left hand side is a tuple of variables. Naturally, the number of values much always matches the number of variables:

>>> (a, b, c, d) = (4, 3, 2)

ValueError: need more than 3 values to unpack

USING LISTS

Lists are similar to tuples: they store a range of values and are defined in a similar fashion. However, unlike tuples, you can modify them. This makes them the normal choice when it comes to storing lists. Here’s an example of a list:

team =[ ‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’]

Notice that the only difference in syntax is the use of square brackets instead of parentheses. Like tuples, the spaces after the comma are a standard practice for increasing readability.

Recalling the values stored in the list are also similar to calling values in a tuple:

print team [3]

Harrison

Like tuples, you can also call values from a range within the list. For example, team [1:3] will recall 3rd and 4th members of the team.

The important thing with lists is its ability to allow change. This is crucial when you are building databases that store values (e.g. a grocery store’s inventory will have changing values of the stock and need to be updated regularly).

Let’s say you induct another member into your team, how will you add him/her?

Values can be added using the'append()' function. The syntax of the append function is of the form:

list_name.append(value-to-add)

Hence, for a new member, Gabriel:

team.append(‘Gabriel')

And done! The new member’s name is added after the last value stored in the list (‘Harrison’).

How do you remove an item from a list? Suppose Michel is not getting along with Azazel and Gabriel, and is lowering the moral of the team, etc.

To delete a value from the list, you use ‘del’. Recall how Python indexes the lists, beginning from zero and onwards. So Michel is the second value on the list, making its index numbering ‘1’.

#Removing Michel from the list

team =[ ‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’, Gabriel]

del team[1]

You can delete a range from the list by assigning an empty list to them:

team [1:3] = []

Now the team the last three names removed from it.

What if you wanted to add a new team member right after Michel? Normally, append[ ] adds the new value at the end of the list.

You simply tell after which member the new member should be placed. This is called slicing the list:

>>>team =[ ‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’]

>>>team [1:1] = [‘Gabriel’]

team =[ ‘Sam’, ‘Michel’, ‘Gabriel’, ‘Azazel’, ‘Harrison’]

METHODS  THAT CAN BE USED WITH LISTS

.append is just one of the several methods that are extensively used with creating lists. Other methods include the following:

.insert it is used for posting a new entry at the specified index number. For example, want to add numbers to your list of team:

>> team.insert(1, 3320) 

This inserts the number 3320 at position 1, shifting the other values up i.e. 2nd becomes 3rd and so on.

If you want to repeat the list within itself, then you will simply use.extend in it.

>>> team.extend ([‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’])

>>> mylist

[‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’, ‘Sam’, ‘Michel’, ‘Azazel’, ‘Harrison’]

If you want to find the index number of any value in the list use .index

>>> team.index(3)

‘Harrison’

Reverse the whole list using .reverse

>>> team.reverse()

[‘Harrison’, ‘Azazel’, ‘Michel’, ‘Sam’]

Remove the a repetitive item or the first use of any item using.remove

>>> team.remove(‘Sam’)            

[‘Michel’, ‘Azazel’, ‘Harrison’]

Or in case you have a number list, and you want to sort them in ascending order, use .sort

>>> numlist.sort()

[1, 3, 3, 3, 7, 9, 10, 10, 24]

USING DICTIONARIES

Previously we have created lists of names of a team and a tuple with variable and value assignment. However, in both of them, the value of the indexed variable can only be called by giving the index number for that value.

What if you want to create a database, or a small phonebook, that gives you the details of a variable when you enter its name instead of the index number?  Lists and tuples cannot give you the required accessibility.

Dictionaries can.

Recall that dictionaries have keys and values. In a phone book, you have names of the people and their contact details. See any similarities?

Creating a dictionary is similar to making a list or a tuple, except a slight difference in its brackets.

·               (Tuples) use parenthesis

·               [Lists] use square brackets

·               {Dictionaries} use curly braces.

Here’s an example of a database for money owed to each member your business team:

#Initial business funds:

Logbook = {‘Sam Kim’: 4000, ‘Michel Sanderson’: 4300, \

Stark Garret': 5120, ‘ Azazel Forest’: 3230, ‘Harrison Snow’: 6300 }

Notice the syntax:

Key: Value

Here is how the keys are used to look up the corresponding value, just like in a dictionary:

>>> print(logbook["Azazel Forest"])

3230

DICTIONARY OPERATIONS

You can add newkey:value pairs in the dictionary as well as  remove and update existing dictionary entries.

ADDING NEW ENTRIES TO DICTIONARIES

To add new entries in your existing dictionary, you simply define them as follows:

#Adding Gabriel to the logbook:

logbook[‘Gabriel Sky'] = 7300

The above states that the key : value = ‘Gabriel Sky’ : 7300

DELETING ENTRIES

Now what if you want to delete some entries? This is done exactly how it was done for lists. Now let’s say Michel has been paid in full, and he has resigned. You want to delete his account permanently. Just like with the lists, you use ‘del’:

del phonebook['Michel Sanderson’]

The ‘del’ operator will delete any variable, entry, or function in a list or a dictionary. Another example is of a small inventory in a grocery store. The dictionary contains the names of various fruits and their availability (number in stock):

>>> inventory = {"apples": 350, "bananas": 230, "Mangos": 100, "Peaches": 250}

>>> print(inventory)

Now what if Mangos go out of stock? We have two options: of deleting the key:value or simply change the value of the key:

#deleting the value

>>> del inventory["mangos"]

>>> print (inventory)

{"apples": 350, "bananas": 230, "Peaches": 250}

In case the store is receiving more stock, the we need the option to simply update the value with a new value:

    >>> inventory["Mangos"] = 0

    >>> print(inventory)

{“Mangos”: 0, "apples": 350, "bananas": 230, "Peaches": 250}

Let’s say we have a new shipment for Mango within the hour, and it will add 150 additional Mangos to the inventory. This can be handled like this:

>>> inventory ["Mangos"] += 150

>>> print (inventory)

{“Mangos”: 150, "apples": 350, "bananas": 230, "Peaches": 250}

Tuples, lists, and dictionaries play an important role in writing simpler and more powerful codes in Python. They become even more important when we start programming using and interfacing objects.