Introduction

In this tutorial you will learn about three very important data structures in Python: lists, tuples, and dictionaries. These structures play important roles in Python and and provide simple but effective ways of manipulating data.

This tutorial assumes some basic knowledge of Python, such as syntax, basic language constructs, data types, and variables. If you are just starting out with Python, it may help to read my other tutorial, Introduction to Python, first.

Lists

A list in Python is a dynamic container that can hold an unlimited number of elements. Items can be added to and removed from the list, and the items need not be homogeneous. In other words, a list can hold items of differing types.

To declare a list in Python, we use square brackets "[]" around a list of objects, or empty square brackets to declare an empty list:

 
#declare an empty list
my_list = []
 
#a list with 7 integer elements
my_other_list = [1, 2, 5, 7, 10, 3, 8]
 
#a list with elements of different types
yet_another_list = [7, "hello world", 5.235, True, 3, 6]

Lists can be indexed like arrays, beginning with offset zero:

my_list = [7, "hello world", 5.235, True, 3, 6]

print my_list[1]  #prints "hello world"
print my_list[4]  #prints "3"

A subset of a list can be obtained by specifying a beginning and ending index. All elements from the beginning index up to (but not including) the end index will be included in the result. Leaving off either the beginning or end index will include all items from the beginning or to the end, respectively.

original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
subset_list = original_list[3:11]
#subset contains [4, 5, 6, 7, 8, 9, 10, 11]
 
subset_list = original_list[:5]
#subset contains [1, 2, 3, 4, 5]
 
subset_list = original_list[:5]
#subset contains [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

There are a number of methods available for manipulating lists, allowing them to be used as other data structures as well, such as queues and stacks.

my_list = [1, 2, 3]
my_list.append("hello")
#my_list now contains [1, 2, 3, "hello"]
 
my_list.append(["hello", 4, 5, 6])
#my_list now contains [1, 2, 3, ["hello", 4, 5, 6]]

notice that the entire list was appended as an object

my_list.extend(["hello", 4, 5, 6])

my_list now contains [1, 2, 3, "hello", 4, 5, 6][/code]

this time, individual elements are appended

Tuples

A tuple, like a list, is a container that can hold an arbitrary number of heterogeneous objects. However, tuples are immutable, that is, their elements cannot be modified, and elements cannot be added to/removed from the tuple.

Tuples can be created by specifying a set of objects separated by commas:

my_tuple = "hello", 4, 27.89

Parentheses are optional when creating a tuple, but are necessary when declaring an empty tuple or creating nested tuples:

#an empty tuple
my_tuple = ()
 
#a nested tuple
my_tuple = ("hello", ("4, True, "python"))

Tuples are especially useful for returning mutiple values from a function:

def getNameAndAge():
    return name, age
 
results = getNameAndAge()

Tuples can be unpacked into individual variables as well:

my_tuple = ("hello", 56, True)
my_string, my_num, my_bool = my_tuple

Using the same concept, we can even use unpacking to directly receive our return values from the function above:

name, age = getNameAndAge()

Dictionaries

A dictionary maps a set of objects (keys) to another set of objects (values). A dictionary works similarly to an associative array or map in other languages. Dictionaries, like lists, are mutable.

Dictionaries can be created in a number of ways. A common way is to create a list of key/value pairs within curly braces:

# key/value pairs
my_dict = {'name':'Jeff', 'age':23, 'member':True}

Another way is to create a list of pairs using the dict() constructor:

# list of pairs
my_dict = dict([('name', 'Jeff'), ('age', 23), ('member', True)])

And if all of your keys are going to be strings, you can simply use the assignment operator to create the pairs:

# using the assignment operator
my_dict = dict(foo=12, bar=18, baz=244)

Individual elements of a dictionary can be added, accessed, changed, and removed by using the index operator ( [] ) to access the elements by the keys:

my_dict = {'name':'Jeff', 'age':23, 'member':True}
 
# access
print my_dict['name']
 
# modify
my_dict['name'] = 'Bill'
 
# add
my_dict['height'] = 72
 
# delete
del my_dict['age']

Conclusion

You should now have a brief understanding of three of Python's most common data structures. There is much more to learn about each of these structures, but such intricacies will have to wait until future tutorials. In the meantime, check out the Python documentation on data structures for more information on methods specific to each structure.

I always welcome questions or feedback about this tutorial. Simply post a reply or PM me; I'm glad to help!

This page was published on It was last revised on

Contributing Authors

0

0 Comments

  • Votes
  • Oldest
  • Latest