SlideShare uma empresa Scribd logo
1 de 88
Baixar para ler offline
Engr. Ranel O. Padon 
PYTHON PROGRAMMING 
V. SEQUENCES 
& 
DICTIONARIES 
1
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
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
DATA STRUCTURES 
Data structures are structures that hold and organize data or information. 
4
SEQUENCES 
Sequences, often called arrays in other languages, 
are data structures that store related data items. 
5
SEQUENCES 
Python supports three basic sequence data types: 
a string, a tuple, and a list. 
6
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
SEQUENCES 
8
SEQUENCES 
9
SEQUENCES 
Sequences can be accessed from the end of the 
sequence by using negative subscripts. 
10
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
SEQUENCES | IMMUTABLE 
12
SEQUENCES 
Python’s Tuple data structure is similar to 
Java’s native array and C’s native array, both of which 
have fixed length. 
13
SEQUENCES 
Some sequences are mutable or can be altered. 
Python lists are mutable sequences. 
In other words, they are Read/Write data structure. 
14
SEQUENCES | MUTABLE 
15
SEQUENCES 
Python’s List data structure is analogous to 
Java’s ArrayList and Vector classes, both of which are extendable. 
16
SEQUENCES 
The length of the sequence is determined 
by the function call len(sequence ). 
This is useful when traversing the sequence. 
17
SEQUENCES | len FUNCTION 
The length of the sequence is determined 
by the function call len(sequence ). 
This is useful when traversing the sequence. 
18
SEQUENCES | len FUNCTION 
Same result with that of previous implementation, 
but more maintainable and scalable. 
19
SEQUENCES | EMPTY STRING 
20
SEQUENCES | EMPTY LIST 
21
SEQUENCES | EMPTY TUPLE 
22
SEQUENCES | TUPLE | SINGLETON 
Tuple with single element must still include a comma. 
Parenthesis is optional in all type of Tuples, singleton or not. 
23
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
SEQUENCES | TUPLE | (UN)PACKING 
25
SEQUENCES | TUPLE | (UN)PACKING 
Tuple packing/unpacking is useful when swapping variables. 
26
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
SEQUENCES 
28
SEQUENCES 
29
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
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
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
SEQUENCES 
33
SEQUENCES 
34
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
SEQUENCES 
36
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
SEQUENCES | SLICING 
38
SEQUENCES | SLICING 
is equivalent to the following expressions: 
sequence [ 0 : len( sequence ) ] 
sequence [ : len( sequence ) ] 
sequence [ 0 : ] 
39
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
DICTIONARIES | EMPTY DICTIONARY 
To create an empty dictionary, use empty curly braces. 
41
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
DICTIONARIES 
43
DICTIONARIES 
44
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
DICTIONARIES | READ 
Dictionary values are accessed with the expression dictionaryName[ key ]. 
46
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
DICTIONARIES | WRITE 
To insert a new key-value pair in a dictionary, use the statement 
dictionaryName[ key ] = value. 
48
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
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
METHODS | APPEND 
List method append adds an items to the end of a list. 
51
METHODS | APPEND 
52
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
METHODS | APPEND 
54
METHODS | LIST 
55
METHODS | SORT 
56
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
METHODS | ITEMS, KEYS, VALUES 
58
METHODS | ITEMS, KEYS, VALUES 
59
METHODS | DICTIONARIES 
60
METHODS | DICTIONARIES 
61
METHODS | LIST | DEL 
62
METHODS | DICTIONARY | DEL 
63
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
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
METHODS | DEEP COPY 
66
METHODS | DEEP COPY 
67
PASS BY REFERENCE 
Python arguments are always passed by object reference, 
that is, the function receives references to the values 
passed as arguments. 
68
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
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
SEQUENCES AS ARGUMENTS 
To pass a list argument to a function, specify the 
name of the list without square brackets. 
71
SEQUENCES AS ARGUMENTS 
72
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
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
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
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
SEQUENCES | MULTI-DIMENSIONAL 
77
SEQUENCES | MULTI-DIMENSIONAL 
78
SEQUENCES | MULTI-DIMENSIONAL 
79
SEQUENCES | MULTI-DIMENSIONAL 
Getting the sum of all elements in a 2-dimensional list. 
Useful for Reading values only. 
80
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
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
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
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
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
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
PRACTICE EXERCISE 4 
Make a transpose function so that a given 2D list, say, 
will be converted/transposed to this: 
87
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

Mais conteúdo relacionado

Mais procurados

Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

Mais procurados (20)

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
OOP Principles
OOP PrinciplesOOP Principles
OOP Principles
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
C++ classes
C++ classesC++ classes
C++ classes
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
JSpiders - Wrapper classes
JSpiders - Wrapper classesJSpiders - Wrapper classes
JSpiders - Wrapper classes
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 

Destaque

Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
Ranel Padon
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
Ranel Padon
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
Ranel Padon
 
Python Programming - XIII. GUI Programming
Python Programming - XIII. GUI ProgrammingPython Programming - XIII. GUI Programming
Python Programming - XIII. GUI Programming
Ranel Padon
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
Ranel Padon
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
Ranel Padon
 

Destaque (12)

Python Programming - III. Controlling the Flow
Python Programming - III. Controlling the FlowPython Programming - III. Controlling the Flow
Python Programming - III. Controlling the Flow
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
Python Programming - XIII. GUI Programming
Python Programming - XIII. GUI ProgrammingPython Programming - XIII. GUI Programming
Python Programming - XIII. GUI Programming
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
 
Switchable Map APIs with Drupal
Switchable Map APIs with DrupalSwitchable Map APIs with Drupal
Switchable Map APIs with Drupal
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 

Semelhante a Python Programming - V. Sequences (List and Tuples) and Dictionaries

Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 

Semelhante a Python Programming - V. Sequences (List and Tuples) and Dictionaries (20)

MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptx
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
AI_2nd Lab.pptx
AI_2nd Lab.pptxAI_2nd Lab.pptx
AI_2nd Lab.pptx
 
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdfTuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
 
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptxChapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
 
Pa1 session 2
Pa1 session 2 Pa1 session 2
Pa1 session 2
 
Unit 1 polynomial manipulation
Unit 1   polynomial manipulationUnit 1   polynomial manipulation
Unit 1 polynomial manipulation
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Pa2 session 1
Pa2 session 1Pa2 session 1
Pa2 session 1
 
Python Basics.pptx
Python Basics.pptxPython Basics.pptx
Python Basics.pptx
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
Python programming
Python programmingPython programming
Python programming
 
easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
 
trisha comp ppt.pptx
trisha comp ppt.pptxtrisha comp ppt.pptx
trisha comp ppt.pptx
 
Python_basics.pptx
Python_basics.pptxPython_basics.pptx
Python_basics.pptx
 
Computer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in pythonComputer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in python
 

Mais de Ranel Padon

Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Ranel Padon
 
PyCon PH 2014 - GeoComputation
PyCon PH 2014 - GeoComputationPyCon PH 2014 - GeoComputation
PyCon PH 2014 - GeoComputation
Ranel Padon
 
Web Mapping with Drupal
Web Mapping with DrupalWeb Mapping with Drupal
Web Mapping with Drupal
Ranel Padon
 

Mais de Ranel Padon (8)

The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)
The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)
The Synergy of Drupal Hooks/APIs (Custom Module Development with ChartJS)
 
CKEditor Widgets with Drupal
CKEditor Widgets with DrupalCKEditor Widgets with Drupal
CKEditor Widgets with Drupal
 
Views Unlimited: Unleashing the Power of Drupal's Views Module
Views Unlimited: Unleashing the Power of Drupal's Views ModuleViews Unlimited: Unleashing the Power of Drupal's Views Module
Views Unlimited: Unleashing the Power of Drupal's Views Module
 
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
 
PyCon PH 2014 - GeoComputation
PyCon PH 2014 - GeoComputationPyCon PH 2014 - GeoComputation
PyCon PH 2014 - GeoComputation
 
Power and Elegance - Leaflet + jQuery
Power and Elegance - Leaflet + jQueryPower and Elegance - Leaflet + jQuery
Power and Elegance - Leaflet + jQuery
 
Of Nodes and Maps (Web Mapping with Drupal - Part II)
Of Nodes and Maps (Web Mapping with Drupal - Part II)Of Nodes and Maps (Web Mapping with Drupal - Part II)
Of Nodes and Maps (Web Mapping with Drupal - Part II)
 
Web Mapping with Drupal
Web Mapping with DrupalWeb Mapping with Drupal
Web Mapping with Drupal
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

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
  • 6. SEQUENCES Python supports three basic sequence data types: a string, a tuple, and a list. 6
  • 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
  • 13. SEQUENCES Python’s Tuple data structure is similar to Java’s native array and C’s native array, both of which have fixed length. 13
  • 14. SEQUENCES Some sequences are mutable or can be altered. Python lists are mutable sequences. In other words, they are Read/Write data structure. 14
  • 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
  • 20. SEQUENCES | EMPTY STRING 20
  • 21. SEQUENCES | EMPTY LIST 21
  • 22. SEQUENCES | EMPTY TUPLE 22
  • 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
  • 25. SEQUENCES | TUPLE | (UN)PACKING 25
  • 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
  • 58. METHODS | ITEMS, KEYS, VALUES 58
  • 59. METHODS | ITEMS, KEYS, VALUES 59
  • 62. METHODS | LIST | DEL 62
  • 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
  • 66. METHODS | DEEP COPY 66
  • 67. METHODS | DEEP COPY 67
  • 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