Python Programming - V. Sequences (List and Tuples) and Dictionaries
1. Engr. Ranel O. Padon
PYTHON PROGRAMMING
V. SEQUENCES
&
DICTIONARIES
1
2. PYTHON PROGRAMMING TOPICS
I
• Introduction to Python Programming
II
• Python Basics
III
• Controlling the Program Flow
IV
• Program Components: Functions, Classes, Packages, and Modules
V
• Sequences (List and Tuples), and Dictionaries
VI
• Object-Based Programming: Classes and Objects
VII
• Customizing Classes and Operator Overloading
VIII
• Object-Oriented Programming: Inheritance and Polymorphism
IX
• Randomization Algorithms
X
• Exception Handling and Assertions
XI
• String Manipulation and Regular Expressions
XII
• File Handling and Processing
XIII
• GUI Programming Using Tkinter
2
3. SEQUENCES AND DICTIONARIES
I
• Introduction to Python Programming
II
• Python Basics
III
• Controlling the Program Flow
IV
• Program Components: Functions, Classes, Packages, and Modules
V
• Sequences (List and Tuples), and Dictionaries
VI
• Object-Based Programming: Classes and Objects
VII
• Customizing Classes and Operator Overloading
VIII
• Object-Oriented Programming: Inheritance and Polymorphism
IX
• Randomization Algorithms
X
• Exception Handling and Assertions
XI
• String Manipulation and Regular Expressions
XII
• File Handling and Processing
XIII
• GUI Programming Using Tkinter
3
4. DATA STRUCTURES
Data structures are structures that hold and organize data or information.
4
5. SEQUENCES
Sequences, often called arrays in other languages,
are data structures that store related data items.
5
7. SEQUENCES
A sequence element may be referenced by writing the sequence name
followed by the element’s position number in square brackets ([ ]).
The first element in a sequence is the zeroth element.
7
10. SEQUENCES
Sequences can be accessed from the end of the
sequence by using negative subscripts.
10
11. SEQUENCES
Some types of sequences are immutable, that is,
the sequence cannot be altered
(e.g., changing the value of one of its elements).
Python strings and tuples are immutable sequences.
In other words, they are Read-Only.
11
16. SEQUENCES
Python’s List data structure is analogous to
Java’s ArrayList and Vector classes, both of which are extendable.
16
17. SEQUENCES
The length of the sequence is determined
by the function call len(sequence ).
This is useful when traversing the sequence.
17
18. SEQUENCES | len FUNCTION
The length of the sequence is determined
by the function call len(sequence ).
This is useful when traversing the sequence.
18
19. SEQUENCES | len FUNCTION
Same result with that of previous implementation,
but more maintainable and scalable.
19
23. SEQUENCES | TUPLE | SINGLETON
Tuple with single element must still include a comma.
Parenthesis is optional in all type of Tuples, singleton or not.
23
24. SEQUENCES | TUPLE | (UN)PACKING
Sequences can be unpacked, the values stored in the sequence are
assigned to various identifiers.
Unpacking is a useful programming shortcut for assigning values to multiple
variables in a single statement.
24
26. SEQUENCES | TUPLE | (UN)PACKING
Tuple packing/unpacking is useful when swapping variables.
26
27. SEQUENCES
The += augmented assignment statement can insert a value in a list.
When the value to the left of the += symbol is a sequence,
the value to the right of the symbol must be a sequence also.
27
30. SEQUENCES
Lists are not restricted to homogeneous data types.
Python programmers typically use lists to store sequences
of homogeneous values (values of the same data type)
30
31. SEQUENCES
In general, a program uses a list to store homogeneous values for the
purpose of looping over these values and performing the same operation
on each value.
Usually, the length of the list is not predetermined and
may vary over the course of the program.
31
32. SEQUENCES
The for/in structure iterates over a sequence.
The for structure starts with the first element in the sequence,
assigns the value of the first element to the control variable
and executes the body of the for structure.
Then, the for structure proceeds to the next element in the sequence
and performs the same operations.
32
35. SEQUENCES
Tuples store sequences of heterogeneous data.
Each data piece in a tuple represents a part of the
total information represented by the tuple.
Usually, the length of the tuple is predetermined and
does not change over the course of a program’s execution.
35
37. SEQUENCES | SLICING
Python provides the slicing capability to obtain contiguous regions
of a sequence.
Slicing creates a new sequence; therefore, when a program
passes a slice to a function, the original sequence is not affected.
37
39. SEQUENCES | SLICING
is equivalent to the following expressions:
sequence [ 0 : len( sequence ) ]
sequence [ : len( sequence ) ]
sequence [ 0 : ]
39
40. DICTIONARIES
The dictionary is a mapping construct that consists of
key-value pairs. Like a physical dictionary, it has listing of words
and definitions.
Dictionaries (called associative arrays in PHP, hash maps/tables in Java,
and analogous to JavaScript Object Notation), can be thought of as
unordered collections of values where each value is accessed
through its corresponding key.
40
41. DICTIONARIES | EMPTY DICTIONARY
To create an empty dictionary, use empty curly braces.
41
42. DICTIONARIES
To create a dictionary with values, use a comma-separated sequence of
key-value pairs, inside curly braces.
Each key-value pair is of the form key : value.
42
45. DICTIONARIES
Python dictionary keys must be immutable values, like strings,
numbers or tuples, whose elements are immutable.
Dictionary values can be of any Python data type.
45
46. DICTIONARIES | READ
Dictionary values are accessed with the expression dictionaryName[ key ].
46
47. DICTIONARIES | READ
Accessing a non-existent dictionary key causes the program to exit
and to display a “key error” message. Use a fail-safe approach.
47
48. DICTIONARIES | WRITE
To insert a new key-value pair in a dictionary, use the statement
dictionaryName[ key ] = value.
48
49. DICTIONARIES | WRITE
The statement dictionaryName [ key ] = value modifies the
value associated with key, if the dictionary already contains that key.
Otherwise, the statement inserts the key-value pair into the dictionary.
49
50. METHODS
A method performs the behaviors (tasks) of an object.
To invoke an object’s method, specify the name of the object,
followed by the dot (.) access operator, followed by the
method invocation.
50
51. METHODS | APPEND
List method append adds an items to the end of a list.
51
53. METHODS | COUNT
List method count takes a value as an argument and returns
the number of elements in the list that have that value.
If the list contains no elements with the specified value, method count
returns 0.
53
57. METHODS | ITEMS, KEYS, VALUES
Dictionary method items returns a list of tuples,
where each tuple contains a key-value pair.
Dictionary method keys returns an unordered list
of the dictionary’s keys.
Dictionary method values returns an unordered list
of the dictionary’s values.
57
64. METHODS | COPY
Dictionary method copy returns a new dictionary
that is a shallow copy of the original dictionary.
In a shallow copy, the elements in the new dictionary
are references only to the elements in the original
dictionary.
64
65. METHODS | DEEP COPY
If the programmer wants to create a copy
(called a deep copy), that is independent of
the original dictionary, Python provides module copy.
Function copy.deepcopy returns a deep copy
of its argument.
65
68. PASS BY REFERENCE
Python arguments are always passed by object reference,
that is, the function receives references to the values
passed as arguments.
68
69. PASS BY REFERENCE
If a function receives a reference to a mutable object
(e.g., a dictionary or a list), the function can modify the
original value of the object.
It is as if the object had been passed by reference.
69
70. PASS BY VALUE
If a function receives a reference to an immutable object
(e.g., a number, a string or a tuple whose elements are
immutable values), the function cannot modify the
original object directly.
It is as if the object had been passed by value.
70
71. SEQUENCES AS ARGUMENTS
To pass a list argument to a function, specify the
name of the list without square brackets.
71
73. SEQUENCES | MULTI-DIMENSIONAL
Sequences can contain elements that are also sequences.
Such sequences have multiple subscripts.
A common use of multiple-subscripted sequences is to
represent tables of values consisting of in formation arranged
in rows and columns.
73
74. SEQUENCES | MULTI-DIMENSIONAL
To identify a particular table element, we must specify two subscripts:
the first identifies the element’s row,
the second identifies the element’s column.
74
75. SEQUENCES | MULTI-DIMENSIONAL
Python does not support multiple-subscripted sequences directly,
but allows programmers to specify single-subscripted tuples
and lists whose elements are also single-subscripted tuples and lists,
thus achieving the same effect.
75
76. SEQUENCES | MULTI-DIMENSIONAL
The name of every element in a multiple-subscripted sequence
is of the form a[ i ][ j ], where
a is the name of the sequence, and
i and j are the subscripts that uniquely identify the
row and column of each element
in the sequence.
76
80. SEQUENCES | MULTI-DIMENSIONAL
Getting the sum of all elements in a 2-dimensional list.
Useful for Reading values only.
80
81. SEQUENCES | MULTI-DIMENSIONAL
Getting the sum of all elements in a 2-dimensional list
using the indices/subscripts. Subscripts are useful also for
overriding the array data.
81
82. SEQUENCES | MULTI-DIMENSIONAL
To compute pure numerical problems (i.e., multi-dimensional arrays),
You might want to use the NumPy (Numerical Python) package
This package contains modules that handle arrays and provides multi-dimensional
array objects for efficient computation.
82
83. Operator Description
f(parameters)
Function Call
x.f(parameters)
Method Call
x[index]
Read from an Element
x[index]
=
value
Write to an Element
x[start:end]
Slicing/Copying
(value,
…)
Tuple Expression/Packing
[value,
…]
List Expression
{key:value,
…}
Dictionary Expression
END NOTES
83
84. PRACTICE EXERCISE 1
Make a diagonal_elements(m) function so that a given 2D list,
say matrix m,
will have all of its diagonal elements be returned in a list
be and printed.
def diagonal_elements(m)
print diagonal_elements(my_2d_list)
84
85. PRACTICE EXERCISE 2
Make a scalar_product(m, s) function so that a given 2D list,
say matrix m,
will have all of its elements be multiplied by the given
scalar/number s. You could either modify the input matrix
or return an independent copy of the modified matrix
def scalar_product(m, s)
print scalar_product(my_2d_list, 2)
85
86. PRACTICE EXERCISE 3
Make a column_sum(m, c) function so that a given 2D list,
say matrix m,
will have all of its elements along column c be added.
Return a single number
def column_sum(m, c)
print column_sum(my_2d_list, 2)
86
87. PRACTICE EXERCISE 4
Make a transpose function so that a given 2D list, say,
will be converted/transposed to this:
87
88. REFERENCES
q Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).
q Disclaimer: Most of the images/information used here have no proper source
citation, and I do not claim ownership of these either. I don’t want to reinvent the
wheel, and I just want to reuse and reintegrate materials that I think are useful or
cool, then present them in another light, form, or perspective. Moreover, the
images/information here are mainly used for illustration/educational purposes
only, in the spirit of openness of data, spreading light, and empowering people
with knowledge. J
88