python programming - v. sequences (list and tuples) and dictionaries

88
Engr. Ranel O. Padon V. SEQUENCES & DICTIONARIES PYTHON PROGRAMMING 1

Upload: engr-ranel-padon

Post on 10-May-2015

1.072 views

Category:

Technology


6 download

DESCRIPTION

Feel free to download the material for offline viewing later, better images' resolutions, and crispier fonts.

TRANSCRIPT

Page 1: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Engr. Ranel O. Padon

V. SEQUENCES & DICTIONARIES

PYTHON PROGRAMMING

1

Page 2: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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

Page 3: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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

Page 4: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Data structures are structures that hold and organize data or information.

DATA STRUCTURES

4

Page 5: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Sequences, often called arrays in other languages, are data structures that store related data items.

SEQUENCES

5

Page 6: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Python supports three basic sequence data types: a string, a tuple, and a list.

SEQUENCES

6

Page 7: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

7

Page 8: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

8

Page 9: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

9

Page 10: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Sequences can be accessed from the end of the sequence by using negative subscripts.

SEQUENCES

10

Page 11: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

11

Page 12: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | IMMUTABLE

12

Page 13: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Python’s Tuple data structure is similar to Java’s native array and C’s native array, both of which have fixed length.

SEQUENCES

13

Page 14: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Some sequences are mutable or can be altered. Python lists are mutable sequences. In other words, they are Read/Write data structure.

SEQUENCES

14

Page 15: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | MUTABLE

15

Page 16: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Python’s List data structure is analogous to Java’s ArrayList and Vector classes, both of which are extendable.

SEQUENCES

16

Page 17: Python Programming - V. Sequences (List and Tuples) and Dictionaries

The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.

SEQUENCES

17

Page 18: Python Programming - V. Sequences (List and Tuples) and Dictionaries

The length of the sequence is determined by the function call len(sequence ). This is useful when traversing the sequence.

SEQUENCES | len FUNCTION

18

Page 19: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | len FUNCTION

Same result with that of previous implementation, but more maintainable and scalable.

19

Page 20: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | EMPTY STRING

20

Page 21: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | EMPTY LIST

21

Page 22: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | EMPTY TUPLE

22

Page 23: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | TUPLE | SINGLETON

Tuple with single element must still include a comma. Parenthesis is optional in all type of Tuples, singleton or not.

23

Page 24: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | TUPLE | (UN)PACKING

24

Page 25: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | TUPLE | (UN)PACKING

25

Page 26: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | TUPLE | (UN)PACKING

Tuple packing/unpacking is useful when swapping variables.

26

Page 27: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

27

Page 28: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

28

Page 29: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

29

Page 30: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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)

SEQUENCES

30

Page 31: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

31

Page 32: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

32

Page 33: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

33

Page 34: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

34

Page 35: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES

35

Page 36: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES

36

Page 37: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | SLICING

37

Page 38: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | SLICING

38

Page 39: Python Programming - V. Sequences (List and Tuples) and Dictionaries

is equivalent to the following expressions: sequence [ 0 : len( sequence ) ] sequence [ : len( sequence ) ] sequence [ 0 : ]

SEQUENCES | SLICING

39

Page 40: Python Programming - V. Sequences (List and Tuples) and 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.

DICTIONARIES

40

Page 41: Python Programming - V. Sequences (List and Tuples) and Dictionaries

To create an empty dictionary, use empty curly braces.

DICTIONARIES | EMPTY DICTIONARY

41

Page 42: Python Programming - V. Sequences (List and Tuples) and 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.

DICTIONARIES

42

Page 43: Python Programming - V. Sequences (List and Tuples) and Dictionaries

DICTIONARIES

43

Page 44: Python Programming - V. Sequences (List and Tuples) and Dictionaries

DICTIONARIES

44

Page 45: Python Programming - V. Sequences (List and Tuples) and 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.

DICTIONARIES

45

Page 46: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Dictionary values are accessed with the expression dictionaryName[ key ].

DICTIONARIES | READ

46

Page 47: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Accessing a non-existent dictionary key causes the program to exit and to display a “key error” message. Use a fail-safe approach.

DICTIONARIES | READ

47

Page 48: Python Programming - V. Sequences (List and Tuples) and Dictionaries

To insert a new key-value pair in a dictionary, use the statement dictionaryName[ key ] = value.

DICTIONARIES | WRITE

48

Page 49: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

DICTIONARIES | WRITE

49

Page 50: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

METHODS

50

Page 51: Python Programming - V. Sequences (List and Tuples) and Dictionaries

List method append adds an items to the end of a list.

METHODS | APPEND

51

Page 52: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | APPEND

52

Page 53: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

METHODS | COUNT

53

Page 54: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | APPEND

54

Page 55: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | LIST

55

Page 56: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | SORT

56

Page 57: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

METHODS | ITEMS, KEYS, VALUES

57

Page 58: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | ITEMS, KEYS, VALUES

58

Page 59: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | ITEMS, KEYS, VALUES

59

Page 60: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | DICTIONARIES

60

Page 61: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | DICTIONARIES

61

Page 62: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | LIST | DEL

62

Page 63: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | DICTIONARY | DEL

63

Page 64: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

METHODS | COPY

64

Page 65: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

METHODS | DEEP COPY

65

Page 66: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | DEEP COPY

66

Page 67: Python Programming - V. Sequences (List and Tuples) and Dictionaries

METHODS | DEEP COPY

67

Page 68: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Python arguments are always passed by object reference, that is, the function receives references to the values passed as arguments.

PASS BY REFERENCE

68

Page 69: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

PASS BY REFERENCE

69

Page 70: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

PASS BY VALUE

70

Page 71: Python Programming - V. Sequences (List and Tuples) and Dictionaries

To pass a list argument to a function, specify the name of the list without square brackets.

SEQUENCES AS ARGUMENTS

71

Page 72: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES AS ARGUMENTS

72

Page 73: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | MULTI-DIMENSIONAL

73

Page 74: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | MULTI-DIMENSIONAL

74

Page 75: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | MULTI-DIMENSIONAL

75

Page 76: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | MULTI-DIMENSIONAL

76

Page 77: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | MULTI-DIMENSIONAL

77

Page 78: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | MULTI-DIMENSIONAL

78

Page 79: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | MULTI-DIMENSIONAL

79

Page 80: Python Programming - V. Sequences (List and Tuples) and Dictionaries

SEQUENCES | MULTI-DIMENSIONAL

Getting the sum of all elements in a 2-dimensional list. Useful for Reading values only.

80

Page 81: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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

Page 82: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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.

SEQUENCES | MULTI-DIMENSIONAL

82

Page 83: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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

Page 84: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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)

PRACTICE EXERCISE 1

84

Page 85: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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)

PRACTICE EXERCISE 2

85

Page 86: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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)

PRACTICE EXERCISE 3

86

Page 87: Python Programming - V. Sequences (List and Tuples) and Dictionaries

Make a transpose function so that a given 2D list, say, will be converted/transposed to this:

PRACTICE EXERCISE 4

87

Page 88: Python Programming - V. Sequences (List and Tuples) and Dictionaries

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