Programming in Python
Programming in Python
Programming in Python
Chapter 6: Lists, Tuples, and
Dictionaries
Xiang Lian
The University of Texas – Pan American
Edinburg, TX 78539
lianx@utpa.edu
1
Objectives
• In this chapter, you will:
– Understand Python sequences
– Learn the list, tuple, and dictionary data types
– Know how to create, initialize, and refer to
individual elements of lists, tuples, and dictionaries
– Explore how to use lists to sort and search
sequences of values
– Learn how to pass lists to functions
– Become familiar with list and dictionary methods
2
Introduction
• Data structures
– Structures that hold and organize information
• Sequences
– Also known as arrays in other languages (e.g., C++)
– Store related data types
– 3 types
• Strings
• Lists
• Tuples
• Mappings
– In most languages called hashes or associative arrays
– Dictionaries are the only python mapping container
• Key-value pairs
3
Sequences
• Sequences
– Series of items that are often related
– Strings are sequences in Python
– A sequence is returned by the range function
4
Example of Sequences
C[0] -45 C[-12]
C[1] 6 C[-11]
Name sequence C[2] 0 C[-10]
(C)
C[3] 72 C[-9]
C[4] 34 C[-8]
C[5] 39 C[-7]
C[6] 98 C[-6]
C[7] -1345 C[-5]
C[8] 939 C[-4]
Position number of
C[9] 10 C[-3]
the element within
sequence C C[10] 40 C[-2]
C[11] 33 C[-1]
5
Sequences (cont'd)
• Elements
– The individual items in each sequence
• Referred to by subscripts
• Obtain one by using sequenceName[ subscript ]
– The subscript of the first element is 0
– The subscript of the last element can be -1
6
Creating Sequences – String
• Strings
– Use quotes
• string1 = "hello"
– Empty string
• string2 = ""
7
Creating Sequences – List
• Lists
– Use brackets
– Separate multiple items with a comma
• list1 = [1, 2, 3, 4]
– Empty list
• list2 = []
• Length of the list
– len (list1)
8
Creating Sequences – Tuple
• Tuples
– Use parenthesis
– Separate multiple items with a comma
• tuple1 = (1, 2, 3, 4)
• tuple1 = 1, 2, 3, 4
– Empty tuple
• tuple2 = ()
– Singleton (or one-element tuple)
• singleton3 = 1,
• Comma (,) after 1 identify the variable signleton3 as a tuple
9
Differences Between Lists and
Tuples
• Differences
– Tuples and lists can both contain the same data
• aList = [ 1, 2, 3, 4 ]
• aTuple = ( 1, 2, 3, 4 )
– For practical purposes though each is used to hold
different types of items
10
Lists
• Not restricted to values of the same type
– Programmers use lists to hold data that is of the
same type
• The length is usually not predetermined and
can vary throughout the program
• Accessing elements out of range
– Python exits and an out of range error is displayed
11
12
# Fig. 5.3: fig05_03.py Outline
# Creating, accessing and changing a list.
print ()
Python 3.4 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> aList = [ 1 ]
>>> print (aList[ 13 ])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
13
14
# Fig. 5.5: fig05_05.py Outline
# Creating a histogram from a list of values.
for i in range( 10 ):
newValue = int( input( "Enter integer %d: " % ( i + 1 ) ) )
values += [ newValue ]
Prompts the user for 10 integers
# create histogram
print ("\nCreating a histogram from values:" )
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ) )
15
16
# Fig. 5.6: fig05_06.py Outline
# Creating and accessing tuples.
17
18
# Fig. 5.7: fig05_07.py Outline
# Unpacking sequences.
# create sequences
aString = "abc" Fig05_07.py
aList = [ 1, 2, 3 ] Creates a sting a list and a tuple
aTuple = "a", "A", 1
19
20
# Fig. 5.8: fig05_08.py Outline
# Slicing sequences.
# create sequences
sliceString = "abcdefghij" Fig05_08.py
sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )
Creates a string a list and a tuple
sliceList = [ "I", "II", "III", "IV", "V",
"VI", "VII", "VIII", "IX", "X" ]
# print strings
print ("sliceString: ", sliceString)
print ("sliceTuple: ", sliceTuple)
print ("sliceList: ", sliceList)
print ()
# get slices
start = int( input( "Enter start: " ) ) Gets a start and end
end = int( input( "Enter end: " ) ) point from the user
# print slices
print ("\nsliceString[", start, ":", end, "] = ", \
sliceString[ start:end ] )
Returns only the data from the
print ("sliceTuple[", start, ":", end, "] = ", \
sliceTuple[ start:end ] ) start point up to the end point
22
23
# Fig. 5.09: fig05_09.py Outline
# Creating, accessing and modifying a dictionary.
24
List Methods
Method Purpose
append( item ) Inserts item at the end of the list.
count( element ) Returns the number of occurrences of element in
the list.
extend( newList ) Inserts the elements of newList at the end of the
list.
index( element ) Returns the index of the first occurrence of
element in the list. If element is not in the list, a
ValueError exception occurs. [Note: We
discuss exceptions in Chapter 12, Exception
Handling.]
insert( index, item ) Inserts item at position index.
pop( [index] ) Parameter index is optional. If this method is
called without arguments, it removes and returns
the last element in the list. If parameter index is
specified, this method removes and returns the
element at position index.
remove( element ) Removes the first occurrence of element from
the list. If element is not in the list, a
ValueError exception occurs.
reverse() Reverses the contents of the list in place (rather
than creating a reversed copy).
sort( [compare- Sorts the content of the list in place. The
function] ) optional parameter compare-function is a
function that specifies the compare criteria. The
compare-function takes any two elements of the
list (x and y) and returns -1 if x should appear
before y, 0 if the orders of x and y do not matter
and 1 if x should appear after y. [Note: We
discuss sorting in Section 5.9.] 25
Fig. 5.12 List methods.
26
# Fig. 5.13: fig05_13.py Outline
# Dictionary methods.
28
References and Reference
Parameters
• Pass-by-value
– Copies the value and passes the copy
• Pass-by-reference
– Allows a function to access the caller data and to modify it
– Can increase performance
• Prevents the copying of large data
– Can weaken security
• Allows direct access to the data
• Pass by object reference
– Only thing allowed in Python
– Combination of pass-by-value and pass-by-reference
– Can modify mutable objects and not immutable objects
29
Passing Lists to Functions
• Passing a list
– The same applies for other mutable objects in
Python
– To pass a list, pass it without its brackets
– This allows the entire list to be changed
– Items in the list that are immutable (numbers or
strings) cannot be changed by the function when
passed individually
30
31
# Fig. 5.16: fig05_16.py Outline
# Passing lists and individual list elements to functions.
32
33
# Fig. 5.17: fig05_17.py Outline
# Sorting a list.
if searchKey in aList:
print ("Found at index:", aList.index( searchKey ) )
else:
The index method is used
print ("Value not found") to find an item in the list
and return the index of that
item
Enter integer search key: 36
Found at index: 18 Program Output