Lists and Tuples - Python Made Easy (2013)

Python Made Easy (2013)

Chapter 4: Lists and Tuples

“In our daily lives as programmers, we process text strings a lot. So I tried to work hard on text processing, namely the string class and regular expressions. Regular expressions are built into the language and are very tuned up for use.”- Yukihiro Matsumoto

In this chapter you will learn about:

· Lists

· Tuples

· Dictionaries

· Accessing lists and dictionaries

· Changing the values in a dictionary

Now that we have built our first program, let's look at some of the more advanced concepts of the language. Python is an in-depth language that provides plenty of functionality, but advanced concepts can get a little overwhelming. Lists are a simple step forward that teaches you some advanced concepts without presenting too much information in one fell swoop.

What Are Lists?

Lists allow you to deal with multiple different data items and process them in a sequence. As we went over earlier, there are multiple different data types that contain more than one item. These include;

· Strings (pieces of text)

· Tuples (lists and ordered groups of several individual items of data)

· Dictionaries (groups of key-value pairs)

These are the most commonly used data types that are able to store multiple different data items. This data can then be accessed using an index.

Accessing Items

Individual items that are contained within a sequence can be obtained using an index. Basically, an index is a number that corresponds with where the data is stored within the sequence. Accessing items that are contained within a tuple is done in the same way that you would access items of any other data type as well. Here is an example of accessing items in a list of tuple;

fruits = ['apples', 'bananas', 'oranges', 'grapes', 'mangos']



Each item contained within the list is represented by a number. The first item in all lists is referred to as“0”. In this example, Apples are 0, bananas are 1, oranges are 2, grapes are 3, and mangoes are 4. You can call on the program to display any of the different fruits, based on where they are contained within the list. There are many ways in which you can access and utilize this data as well, slicing, and pulling individual pieces of data out of each of the data containers within the list. Here is an example of pulling multiple different pieces of data out of a list;

fruits = ['apples', 'bananas', 'oranges', 'grapes', 'mangos']


['oranges', 'mangos']

In this example you call on both 2 and 4, displaying both oranges and mangoes. Accessing items in lists is consistent and quite simple. You can use the same commands across multiple data types, which makes the entire process much easier to handle.

Boolean Statements and Lists

You can also pull boolean statements from lists as well. This is great for situations where you want to check the contents of a list of tuple. Sticking with the fruits example, you can ask the program to check your given list and return whether or not it contains the data that you are looking for.

Does the List contain raspberry?

'raspberry' in fruits


You can also ask it the other way around.

'raspberry' not in fruits


You can also check for specific inclusions in different data containers.

'ana' in 'banana'


Creating Tuples

Tuples as a data type are often used in conjunction with, or to replace lists. Tuples are immutable ordered groups of items or elements. Think of them like containers. Every tuple is made up of many individuals containers that contain data. You specify which container you wou8ld like to access when accessing the data, and then may use that data in a variety of different ways. They are comma-separated lists of values that are enclosed within parenthesis.

Creating a tuple is simple. Here is a command that allows you to create a tuple;

blank_tuple = ()

You have now created a tuple named“blank_tuple” that contains no data as of yet. Remember that all items contained within a tuple must be followed by a comma, even if they are the only item within the tuple. So a tuple that contains a single item would have (item1,) within the parenthesis. Tuples are accessed in the same way that lists are accessed.

Creating Lists

Lists are the most common method for storing multiple values in Python. They are an ordered, comma-separated list that are enclosed within brackets. Lists are different because they can store many different items– they all do not have to be the same data type. Here are some examples provided in an earlier chapter about using lists;

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character

print str * 3 # Prints string three times

print str + "YOYO" # Prints concatenated string

Here are some methods that can be used to append, change, and edit lists that have already been created. These are extremely useful for manipulating data that is already contained within the list, once it has been declared.

list.append(X)– Add an item to the end of your list.

List.extend(L)– This extends the list by appending all of the items that are already contained within the list.

List.insert(i, x)– The insert command allows you to insert an item at a given position. You can choose to insert a new piece of data into the middle of the list, pushing everything behind it farther down.

List.remove(X)– Remove an item from your list, in the position represented by x.

list.pop([i])– Remove an item from the list at the specified postion and return it. If you do not specify a position, the last item in the list will be removed and returned.

List.index(x)– The index command returns the item at the index location that you have called on.

List.reverse() - Reverses all elements within the list.

All off these commands are great ways to append, change, and edit a list that you have already created. You will find that frequently you may want to add item sto a list, or edit data already placed within the list based on the actions of your user.


Other languages refer to dictionaries as associative arrays or associative memories. Dictionaries are indexed by strings and numbers which act like keys. One can also use a tuple as a key. However, the tuple must only contain strings, tuples or numbers.

The {} braces are used to make a dictionary. These contain key:value pairs. Dictionaries wil store values with keys and then, they access or extract the same values using the keys. If you want to delete a key you can so withdel.

It is possible to get a list of the keys by using the key() method. This will give you an entire list of al the keys within the dictionary. Here is the syntax of a dictionary:

dict= {‘Ana’: ‘1980’, ‘Ben’: ‘1930’, ‘Christine’: ‘2012}

How to Access the Values within a Dictionary

You can also access the values within the dictionary by using the square brackets. Here’s how you can do so:

dict = {'Name': 'Chris', 'Age': 20, 'Salary per month': '$20'};

print "dict['Name']: ", dict['Name'];

print "dict['Age']: ", dict['Age'];

As can be seen, the name, age and salary of the employee is defined within the curly brackets. Access is given to them by using the square brackets. When you execute this code you will get:

dict[‘Name’] : Chris

dict[‘Age’]: 20

Always use keys that do exist or else Python will notify you of an error.

You can also update the dictionary or modify it by changing various values within the existing dictionary, too. So, let’s modify the dictionary we used above:

dict = {'Name': 'Chris', 'Age': 20, 'Salary per month': '$20'};

dict[‘Age’ ]= 21

dict [‘Marital Status’]= “Engaged”

print "dict['Name']: ", dict['Name'];

print "dict[Marital Status]: ", dict[Marital Status];

After introducing these changes, you should get the following output:

dict['Age']: 21

dict['Marital Status']: Engaged

Likewise, it is also possible to delete content from the dictionary by using the del statement. Here’s an example of how this can be done:

dict = {'Name': 'Chris', 'Age': 20, 'Salary': '$20'};

del dict['Name'];


del dict ;

print "dict['Age']: ", dict['Age'];

print "dict['Marital Status']: ", dict['Marital Status'];

When executed, this will give you the following result:


Traceback (most recent call last):

File "", line 9, in

print "dict['Age']: ", dict['Age'];

TypeError: 'type' object has no attribute '__getitem__'

Note: You cannot duplicate the same key in a dictionary.

PROJECT: Lists and Tuples

Now you are familiar with lists and tuples, so let's test your skills with a project. Try not to look at the answer until you have finished your own program. In this project we will be making a camping checklist. Create a list named“camping” and include tent, swimwear, cooking supplies, and a first aid kit. Use the append command to add life-jackets. Then, insert hiking boots into position 3 on your list, and display the list.


camping = ['tent', 'swimwear', 'cooking supplies', 'first aid kit']


camping.insert(3, 'hiking boots')

print camping


ü The following was discussed in this chapter:

· How to create lists

· How to create tuples

· What are tuples

· What are dictionaries

· When to use dictionaries

· Accessing dictionaries

· Changing the values within a dictionary