TUTORIAL: Lists, Tuples, and Dictionaries

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

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:

PYTHON Code: [ Select ]
 
#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]
  1.  
  2. #declare an empty list
  3. my_list = []
  4.  
  5. #a list with 7 integer elements
  6. my_other_list = [1, 2, 5, 7, 10, 3, 8]
  7.  
  8. #a list with elements of different types
  9. yet_another_list = [7, "hello world", 5.235, True, 3, 6]


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

PYTHON Code: [ Select ]
my_list = [7, "hello world", 5.235, True, 3, 6]
 
print my_list[1]  #prints "hello world"
print my_list[4]  #prints "3"
  1. my_list = [7, "hello world", 5.235, True, 3, 6]
  2.  
  3. print my_list[1]  #prints "hello world"
  4. 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.

PYTHON Code: [ Select ]
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]
  1. original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  2. subset_list = original_list[3:11]
  3. #subset contains [4, 5, 6, 7, 8, 9, 10, 11]
  4.  
  5. subset_list = original_list[:5]
  6. #subset contains [1, 2, 3, 4, 5]
  7.  
  8. subset_list = original_list[:5]
  9. #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.

PYTHON Code: [ Select ]
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]]
  1. my_list = [1, 2, 3]
  2. my_list.append("hello")
  3. #my_list now contains [1, 2, 3, "hello"]
  4.  
  5. my_list.append(["hello", 4, 5, 6])
  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:

PYTHON Code: [ Select ]
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:

PYTHON Code: [ Select ]
#an empty tuple
my_tuple = ()
 
#a nested tuple
my_tuple = ("hello", ("4, True, "python"))
  1. #an empty tuple
  2. my_tuple = ()
  3.  
  4. #a nested tuple
  5. my_tuple = ("hello", ("4, True, "python"))


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

PYTHON Code: [ Select ]
def getNameAndAge():
    return name, age
 
results = getNameAndAge()
  1. def getNameAndAge():
  2.     return name, age
  3.  
  4. results = getNameAndAge()


Tuples can be unpacked into individual variables as well:

PYTHON Code: [ Select ]
my_tuple = ("hello", 56, True)
my_string, my_num, my_bool = my_tuple
  1. my_tuple = ("hello", 56, True)
  2. 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:

PYTHON Code: [ Select ]
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:

PYTHON Code: [ Select ]
# key/value pairs
my_dict = {'name':'Jeff', 'age':23, 'member':True}
  1. # key/value pairs
  2. my_dict = {'name':'Jeff', 'age':23, 'member':True}


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

PYTHON Code: [ Select ]
# list of pairs
my_dict = dict([('name', 'Jeff'), ('age', 23), ('member', True)])
  1. # list of pairs
  2. 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:

PYTHON Code: [ Select ]
# using the assignment operator
my_dict = dict(foo=12, bar=18, baz=244)
  1. # using the assignment operator
  2. 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 they keys:

PYTHON Code: [ Select ]
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']
  1. my_dict = {'name':'Jeff', 'age':23, 'member':True}
  2.  
  3. # access
  4. print my_dict['name']
  5.  
  6. # modify
  7. my_dict['name'] = 'Bill'
  8.  
  9. # add
  10. my_dict['height'] = 72
  11.  
  12. # delete
  13. 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 mean time, 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!

Post Information

  • Total Posts in this topic: 1 post
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 1 guest
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.