SlideShare a Scribd company logo
1 of 55
Download to read offline
Python & Perl
Lecture 06

Department of Computer Science
Utah State University
Recap
●
●
●
●
●

Types in Python
Built-in Sequences
List: Python's Workhorse
Function parameters
Scoping
Outline
●

Object Comparison

●

Loops

●

Dictionaries
Object Comparison
Object Comparison
●

●

The operators <, >, ==, >=, <=, and != compare the values of
two objects
The objects need not have the same type
Object Comparison
●

●

●

●

●

Numbers are compared arithmetically
Strings are compared lexicographically using the numeric
equivalents of their characters
Tuples and lists are compared lexicographically using
comparison of corresponding elements
Sequences, to compare equal, must be of the same type and
have the same length and the corresponding elements must
compare equal
Mappings (dictionaries) compare equal if and only if their sorted
(key, value) lists compare equal
cmp(x, y)
●

cmp(x, y) is a built-in function

●

cmp(x, y) returns


if

x < y



1

if

x > y


●

-1
0

if

x == y

cmp(x, y) provides the default comparison function for
sort()
cmp(x, y)
>>> cmp(1, 2)
-1
>>> cmp(2, 1)
1
>>> cmp(1, 1)
0
>>> cmp('a', 'b')
-1
>>> cmp('b', 'a')

1
Customizing sort()
●

It is possible to customize sort()

●

Customization requires two steps:


Define a new comparison function that takes two arguments and returns three integers according to
the cmp() convention



Pass the function object (just the function name with
no parenthesis) to sort()
Example 01: Customizing sort()
●

Define a comparator function:
def neg_cmp(x, y):
return -cmp(x,y)

●

Pass the comparator function to sort():
>>> z = [1, 2, 3, 4, 5]
>>> z.sort(neg_cmp)
>>> z
[5, 4, 3, 2, 1]
Loops
C/C++ while vs. Python while
●

Common C/C++ idiom:
while ((x = next()) != NULL) {
// Some code
}

●

Python while loops may not have assignments in the
test statements:
x = next()
while x:
## some code
x = next()
Python while Example
## print numbers from 1 upto 100
x = 1
while x <= 100:
print x
x += 1
Problem

Write a Python script that asks the user for his/her
name until the user actually enters a string
Coding Solution 1
### keep asking for name until the user types
### something; not '' evaluates to True

name = ''
while not name:
name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name
Coding Solution 2
### keep asking for name until the user types
### something that does not consist only of white
### spaces; not '' evaluates to True

name=''
while not name.strip():
name=raw_input('Please enter your name: ')
print 'Hello, %s!' % name
for Loops
●

Syntax
for targetList in IterableObject:
code block

●

●

IterableObject is (usually) a sequence and
returns its elements one at a time in order
targetList is one or more comma separated
reference names
for Loop Example
## prints (1, 2) and (3, 4) on separate
## lines
for x in ((1, 2), (3, 4)):
print x
## prints 1 2 and 3 4 on separate lines
for x,y in ((1, 2), (3, 4)):
print x, y
Loop Else
●

Both for loops and while loops have an extended form not usually seen in
other languages
while expression:
code block
else:
code block
for targetList in IterableObject:
code block
else:
code block
Using Loop Else
●

The else block of a loop is run if the loop exits normally

●

Use of continue allows the loop to exit normally

●

If the loop exits because of a break, the else block is
not run
Builtin Functions Useful in Loops
range([start,] stop [, step])
range()
●

range() generates a list with values of an arithmetic progression

●

Syntax pattern 1: range(stop)
>>> range(5)

## start defaults to 0, step defaults to 1

[0, 1, 2, 3, 4]
>>> range(10) ## start defaults to 0, step defaults to 1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range()
●

range() generates a list with values of an arithmetic progression

●

Syntax pattern 2: range(start,stop )
>>> range(5, 10)

## step defaults to 1

[5, 6, 7, 8, 9]
>>> range(10, 20) ## step defaults to 1
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
range()
●

range() generates a list with values of an arithmetic progression

●

Syntax pattern 3: range(start,stop,step)
>>> range(1, 11, 2)

## odd numbers in [1, 10]

[1, 3, 5, 7, 9]
>>> range(9, -1, -2)

## odd numbers in [1, 10] from

## largest to smallest
[9, 7, 5, 3, 1]
>>> range(10, 0, -2)
[10, 8, 6, 4, 2]

## even numbers from 10 down to 1
## note 0 is not included but 10 is
xrange()
●

range() creates the entire list that contains each element of the
arithmetic progression

●

If the range is too large, this requires a large amount of memory

●

xrange() is an alternative to range() for dealing large ranges

●

●

xrange() uses the same arguments as range() but returns an iterable object that supports lazy iteration: generates each element
in the range one at a time
Bottom line: size of xrange() object is independent of the size
of the range
xrange()
>>> rng = xrange(10, 1000000)
>>> for x in rng:
if x > 999998:
print x
999999
Parallel Iteration
●

If you want to iterate over two sequences at the same
time
names=['a','b','c','d']
ages=[12,15,25,17]

●

To print the names with corresponding ages
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old.'
zip(seq1 [, seq2 [...]] )
Zip
>>> names=['a','b','c','d']
>>> ages=[12,15,25,17]
>>> zip(names,ages)
[('a', 12), ('b', 15), ('c', 25), ('d', 17)]
>>> for name,age in zip(names,ages):
print name, 'is', age, 'years old'
zip()
●

zip() combines one or more sequences into a list of tuples where the n-th element of each tuple is the n-th element in the n-th sequence
>>> zip([1, 2], [3, 4])
[(1, 3), (2, 4)]
>>> zip([1, 2])
[(1,), (2,)]
>>> zip('ab', [3, 4])
[('a', 3), ('b', 4)]
zip()
●

The length of the list returned by zip() is the length of the
shortest sequence
>>> zip([1, 2], [3, 4, 5])
[(1, 3), (2, 4)]
>>> zip('abc', [3, 4])
[('a', 3), ('b', 4)]
zip()
●

zip() can handle ranges
>>> zip(xrange(1, 10), xrange(11, 20))
[(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8,
18), (9, 19)]
>>> zip(range(1, 5), range(6, 10), range(11, 15))
[(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]
zip()
●

zip() can be used in sequence unpacking
>>> x, y = [zip(range(1, 5), range(6, 10)), zip(range(-5, 0),
range(-10, -5))]
>>> x
[(1, 6), (2, 7), (3, 8), (4, 9)]
>>> y
[(-5, -10), (-4, -9), (-3, -8), (-2, -7), (-1, -6)]
enumerate(iterable [, start])
enumerate()
●

●

enumerate() returns an enumeration object
Enumeration objects support the next() method that returns the
tuple (i, j) where i is the number of element j in the enumeration
object
>>> en01 = enumerate(['a', 'b'])
>>> en01.next()
(0, 'a')
>>> en01.next()
(1, 'b')
>>> en01.next()

## error
Dictionaries
Dictionary
●

Dictionary is a set of key-value pairs

●

Dictionaries are mutable

●

●

Dictionary is the only type built-in mapping data
structure
The keys are not ordered
Basic Syntax
●

Dictionary is defined by { }
emptyDict = {} ## defines empty dictionary

●

A key-value pair is defined as key colon value
dict = {'one' : 1}

●

Multiple key-value pairs are separated by commas
dict = {'one' : 1, 'two' : 2, 'three' : 3}
Keys and Values
●

Keys can be any immutable objects: numbers,
characters, tuples, and strings

●

Lists and dictionaries cannot be keys

●

Values can be any objects

●

Dictionaries can be nested, i.e., there can be a
dictionary within another dictionary
Example
box = {'size'

: {'height' : 10,
'width' : 20},

'isCardboard' : True,
'color'
'contents'

: 'red',
: ['nail',
'hammer',
'screw']}
Access
>>> box['size'] # must retrieve on key that exists
{'width': 20, 'height': 10}
>>> box['size']['width']
20
>>> box['contents']
['nail', 'hammer', 'screw']
>>> box['contents'][-1]
'screw'
Access
>>> box.hasKey('size')
True
>>> box.items() # do it only on small dictionaries
[('color', 'red'), ('isCardboard', True), ('contents', ['nail',
'hammer', 'screw']), ('size', {'width': 20, 'height': 10})]
>>> box.items()[0]
('color', 'red')
>>> box.items()[0][-1]
'red'
Adding Key-Value Pairs
●

You can add new key value pairs to the previously
created dictionary
my_dict = {}
for c in 'abcdefg':
my_dict[c.upper()] = c
>>> my_dict
{'A': 'a', 'C': 'c', 'B': 'b', 'E': 'e', 'D': 'd', 'G': 'g', 'F': 'f'}
>>> my_dict[(1, 2)] = [1, 2]
>>> my_dict[(1, 2)]
[1, 2]
Construction
●

The constructor dict() can be used to create dictionaries from a
sequence of two-item sequences
>>> my_dict2 = dict([['A', 'a'], ['B', 'b'], ['C', 'c']])
>>> my_dict2
{'A': 'a', 'C': 'c', 'B': 'b'}
>>> my_dict3 = dict([('A', 'a'), ('B', 'b'), ('C', 'c')])
>>> my_dict3
{'A': 'a', 'C': 'c', 'B': 'b'}
>>> my_dict4 = dict((('A', 'a'), ('B', 'b'), ('C', 'c')))
>>> my_dict4
{'A': 'a', 'C': 'c', 'B': 'b'}
Construction
●

●

●

The constructor dict() can be used to create
dictionaries from keyword-value pairs
The keyword-value pair has the following syntax:
keyword = value
Keywords are converted into strings
>>> my_dict5 = dict(first_name = "John",
last_name = "Nicholson")
>>> my_dict5
{'first_name': 'John', 'last_name': 'Nicholson'}
Checking for Keys
●

Option 1: key in dictionary
>>> my_dict = dict(first_name = "John", last_name =
"Nicholson")
>>> "first_name" in my_dict
True
>>> "middle_name" not in my_dict
True

●

Option 2: dictionary.has_key(<key>)
>>> my_dict.has_key('first_name')
True
Safe Access with get()
●

dict.get() is similar to use dict[] but safer

●

Syntax: dict.get(key[, default])

●

●

●

dict[key] returns the value of key in dict or throws
error if key is not in dict
dict.get(key) returns value of key in dict or None if
key is not in dict
dict.get(key, default) returns value of key in dict
or default if key is not in dict
Example
>>> my_dict = {'one' : 1, 'two' : ['a', 'b', 'c']}
>>> my_dict['one']
1
>>> my_dict['three']

## error

>>> my_dict.get('three') ## None (nothing) returned
>>> my_dict.get('three', 'not in dict')
'not in dict'

## default 'not in dict' returned
Clearing Dictionaries
>>> my_dict = { }
>>> my_dict['one'] = [1, 2, 3]
>>> my_dict['two'] = ['a', 'b', 'c']
>>> my_dict
{'two': ['a', 'b', 'c'], 'one': [1, 2, 3]}
>>> my_dict.clear()
>>> my_dict
{}
Shallow Copying
●

The method copy() returns a shallow copy of the dictionary
my_dict = {'one' : 1, 'two' : ['a', 'b', 'c']}
my_dict2 = my_dict.copy()

print 'shallow copying:', my_dict, my_dict2
del my_dict2['two'][-1]
print 'shallow copying:', my_dict, my_dict2

Output:
shallow copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b', 'c'], 'one': 1}
shallow copying: {'two': ['a', 'b'], 'one': 1} {'two': ['a', 'b'], 'one': 1}
Deep Copying
●

The method deepcopy() returns a deep copy of the dictionary
from copy import deepcopy
my_dict3 = {'one' : 1, 'two' : ['a', 'b', 'c']}
my_dict4 = deepcopy(my_dict3)

print 'deep copying:', my_dict3, my_dict4
del my_dict4['two'][-1]
print 'deep copying:', my_dict3, my_dict4

Output:
deep copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b', 'c'], 'one': 1}
deep copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b'], 'one': 1}
Dictionary Creation From Keys
●

The method fromkeys() creates a dictionary from keys each of
which maps to None
>>> d = {}.fromkeys(['key1', 'key2'])
>>> d
{'key2': None, 'key1': None}
>>> d['key1'] = 'value1'
>>> d['key2'] = 'value2'
>>> d
{'key2': 'value2', 'key1': 'value1'}
Deleting Keys with del()
●

You can use del() to delete key-value pairs from
dictionaries
>>> my_dict
{0: 0, 1: 1, 2: 4, 3: 9}
>>> del my_dict[2]
>>> my_dict
{0: 0, 1: 1, 3: 9}
Reading & References
●

●

●

www.python.org
Ch 03 (Strings), M. L. Hetland. Beginning Python From
nd
Novice to Professional, 2 Ed., APRESS
Ch 05 (Object Comparison, Loops), M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS

More Related Content

What's hot

Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsSunil Yadav
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskellLuca Molteni
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overviewAveic
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheetGil Cohen
 
CS101- Introduction to Computing- Lecture 38
CS101- Introduction to Computing- Lecture 38CS101- Introduction to Computing- Lecture 38
CS101- Introduction to Computing- Lecture 38Bilal Ahmed
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 

What's hot (20)

Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
PDBC
PDBCPDBC
PDBC
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
CS101- Introduction to Computing- Lecture 38
CS101- Introduction to Computing- Lecture 38CS101- Introduction to Computing- Lecture 38
CS101- Introduction to Computing- Lecture 38
 
R programming
R programmingR programming
R programming
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Array
ArrayArray
Array
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 

Viewers also liked

Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Wardah Rosman
 
The New Data Security Risk
The New Data Security RiskThe New Data Security Risk
The New Data Security RiskSteve Kirwan
 
Automated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersAutomated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersIIMnet Ventures
 
Jb slideshow!!
Jb slideshow!!Jb slideshow!!
Jb slideshow!!zoiefuller
 
Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges topillo1
 
UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT Wardah Rosman
 
Presentación1
Presentación1Presentación1
Presentación1topillo1
 

Viewers also liked (8)

Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2Ub0203 developing the skills of academic numeracy & it 2
Ub0203 developing the skills of academic numeracy & it 2
 
The New Data Security Risk
The New Data Security RiskThe New Data Security Risk
The New Data Security Risk
 
Automated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet membersAutomated posting on facebook and twitter for IIMnet members
Automated posting on facebook and twitter for IIMnet members
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
Jb slideshow!!
Jb slideshow!!Jb slideshow!!
Jb slideshow!!
 
Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges Exercicisdetransmissidemovimentambpolitges
Exercicisdetransmissidemovimentambpolitges
 
UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT UB0203 Developing the skills of Academic Numeracy & IT
UB0203 Developing the skills of Academic Numeracy & IT
 
Presentación1
Presentación1Presentación1
Presentación1
 

Similar to Python lecture 05

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environmentYogendra Chaubey
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxSreeLaya9
 
R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academyrajkamaltibacademy
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdfMariappanR3
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 
Introduction to R
Introduction to RIntroduction to R
Introduction to Ragnonchik
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 

Similar to Python lecture 05 (20)

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academy
 
R basics
R basicsR basics
R basics
 
Session 4
Session 4Session 4
Session 4
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
R Basics
R BasicsR Basics
R Basics
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdf
 
R language introduction
R language introductionR language introduction
R language introduction
 
Arrays
ArraysArrays
Arrays
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 

More from Tanwir Zaman

More from Tanwir Zaman (15)

Cs3430 lecture 17
Cs3430 lecture 17Cs3430 lecture 17
Cs3430 lecture 17
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
 
Python lecture 12
Python lecture 12Python lecture 12
Python lecture 12
 
Python lecture 10
Python lecture 10Python lecture 10
Python lecture 10
 
Python lecture 09
Python lecture 09Python lecture 09
Python lecture 09
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
Python lecture 07
Python lecture 07Python lecture 07
Python lecture 07
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Python lecture 01
Python lecture 01Python lecture 01
Python lecture 01
 
Python lecture 11
Python lecture 11Python lecture 11
Python lecture 11
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Python lecture 05

  • 1. Python & Perl Lecture 06 Department of Computer Science Utah State University
  • 2. Recap ● ● ● ● ● Types in Python Built-in Sequences List: Python's Workhorse Function parameters Scoping
  • 5. Object Comparison ● ● The operators <, >, ==, >=, <=, and != compare the values of two objects The objects need not have the same type
  • 6. Object Comparison ● ● ● ● ● Numbers are compared arithmetically Strings are compared lexicographically using the numeric equivalents of their characters Tuples and lists are compared lexicographically using comparison of corresponding elements Sequences, to compare equal, must be of the same type and have the same length and the corresponding elements must compare equal Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal
  • 7. cmp(x, y) ● cmp(x, y) is a built-in function ● cmp(x, y) returns  if x < y  1 if x > y  ● -1 0 if x == y cmp(x, y) provides the default comparison function for sort()
  • 8. cmp(x, y) >>> cmp(1, 2) -1 >>> cmp(2, 1) 1 >>> cmp(1, 1) 0 >>> cmp('a', 'b') -1 >>> cmp('b', 'a') 1
  • 9. Customizing sort() ● It is possible to customize sort() ● Customization requires two steps:  Define a new comparison function that takes two arguments and returns three integers according to the cmp() convention  Pass the function object (just the function name with no parenthesis) to sort()
  • 10. Example 01: Customizing sort() ● Define a comparator function: def neg_cmp(x, y): return -cmp(x,y) ● Pass the comparator function to sort(): >>> z = [1, 2, 3, 4, 5] >>> z.sort(neg_cmp) >>> z [5, 4, 3, 2, 1]
  • 11. Loops
  • 12. C/C++ while vs. Python while ● Common C/C++ idiom: while ((x = next()) != NULL) { // Some code } ● Python while loops may not have assignments in the test statements: x = next() while x: ## some code x = next()
  • 13. Python while Example ## print numbers from 1 upto 100 x = 1 while x <= 100: print x x += 1
  • 14. Problem Write a Python script that asks the user for his/her name until the user actually enters a string
  • 15. Coding Solution 1 ### keep asking for name until the user types ### something; not '' evaluates to True name = '' while not name: name = raw_input('Please enter your name: ') print 'Hello, %s!' % name
  • 16. Coding Solution 2 ### keep asking for name until the user types ### something that does not consist only of white ### spaces; not '' evaluates to True name='' while not name.strip(): name=raw_input('Please enter your name: ') print 'Hello, %s!' % name
  • 17. for Loops ● Syntax for targetList in IterableObject: code block ● ● IterableObject is (usually) a sequence and returns its elements one at a time in order targetList is one or more comma separated reference names
  • 18. for Loop Example ## prints (1, 2) and (3, 4) on separate ## lines for x in ((1, 2), (3, 4)): print x ## prints 1 2 and 3 4 on separate lines for x,y in ((1, 2), (3, 4)): print x, y
  • 19. Loop Else ● Both for loops and while loops have an extended form not usually seen in other languages while expression: code block else: code block for targetList in IterableObject: code block else: code block
  • 20. Using Loop Else ● The else block of a loop is run if the loop exits normally ● Use of continue allows the loop to exit normally ● If the loop exits because of a break, the else block is not run
  • 23. range() ● range() generates a list with values of an arithmetic progression ● Syntax pattern 1: range(stop) >>> range(5) ## start defaults to 0, step defaults to 1 [0, 1, 2, 3, 4] >>> range(10) ## start defaults to 0, step defaults to 1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 24. range() ● range() generates a list with values of an arithmetic progression ● Syntax pattern 2: range(start,stop ) >>> range(5, 10) ## step defaults to 1 [5, 6, 7, 8, 9] >>> range(10, 20) ## step defaults to 1 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
  • 25. range() ● range() generates a list with values of an arithmetic progression ● Syntax pattern 3: range(start,stop,step) >>> range(1, 11, 2) ## odd numbers in [1, 10] [1, 3, 5, 7, 9] >>> range(9, -1, -2) ## odd numbers in [1, 10] from ## largest to smallest [9, 7, 5, 3, 1] >>> range(10, 0, -2) [10, 8, 6, 4, 2] ## even numbers from 10 down to 1 ## note 0 is not included but 10 is
  • 26. xrange() ● range() creates the entire list that contains each element of the arithmetic progression ● If the range is too large, this requires a large amount of memory ● xrange() is an alternative to range() for dealing large ranges ● ● xrange() uses the same arguments as range() but returns an iterable object that supports lazy iteration: generates each element in the range one at a time Bottom line: size of xrange() object is independent of the size of the range
  • 27. xrange() >>> rng = xrange(10, 1000000) >>> for x in rng: if x > 999998: print x 999999
  • 28. Parallel Iteration ● If you want to iterate over two sequences at the same time names=['a','b','c','d'] ages=[12,15,25,17] ● To print the names with corresponding ages for i in range(len(names)): print names[i], 'is', ages[i], 'years old.'
  • 29. zip(seq1 [, seq2 [...]] )
  • 30. Zip >>> names=['a','b','c','d'] >>> ages=[12,15,25,17] >>> zip(names,ages) [('a', 12), ('b', 15), ('c', 25), ('d', 17)] >>> for name,age in zip(names,ages): print name, 'is', age, 'years old'
  • 31. zip() ● zip() combines one or more sequences into a list of tuples where the n-th element of each tuple is the n-th element in the n-th sequence >>> zip([1, 2], [3, 4]) [(1, 3), (2, 4)] >>> zip([1, 2]) [(1,), (2,)] >>> zip('ab', [3, 4]) [('a', 3), ('b', 4)]
  • 32. zip() ● The length of the list returned by zip() is the length of the shortest sequence >>> zip([1, 2], [3, 4, 5]) [(1, 3), (2, 4)] >>> zip('abc', [3, 4]) [('a', 3), ('b', 4)]
  • 33. zip() ● zip() can handle ranges >>> zip(xrange(1, 10), xrange(11, 20)) [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)] >>> zip(range(1, 5), range(6, 10), range(11, 15)) [(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]
  • 34. zip() ● zip() can be used in sequence unpacking >>> x, y = [zip(range(1, 5), range(6, 10)), zip(range(-5, 0), range(-10, -5))] >>> x [(1, 6), (2, 7), (3, 8), (4, 9)] >>> y [(-5, -10), (-4, -9), (-3, -8), (-2, -7), (-1, -6)]
  • 36. enumerate() ● ● enumerate() returns an enumeration object Enumeration objects support the next() method that returns the tuple (i, j) where i is the number of element j in the enumeration object >>> en01 = enumerate(['a', 'b']) >>> en01.next() (0, 'a') >>> en01.next() (1, 'b') >>> en01.next() ## error
  • 38. Dictionary ● Dictionary is a set of key-value pairs ● Dictionaries are mutable ● ● Dictionary is the only type built-in mapping data structure The keys are not ordered
  • 39. Basic Syntax ● Dictionary is defined by { } emptyDict = {} ## defines empty dictionary ● A key-value pair is defined as key colon value dict = {'one' : 1} ● Multiple key-value pairs are separated by commas dict = {'one' : 1, 'two' : 2, 'three' : 3}
  • 40. Keys and Values ● Keys can be any immutable objects: numbers, characters, tuples, and strings ● Lists and dictionaries cannot be keys ● Values can be any objects ● Dictionaries can be nested, i.e., there can be a dictionary within another dictionary
  • 41. Example box = {'size' : {'height' : 10, 'width' : 20}, 'isCardboard' : True, 'color' 'contents' : 'red', : ['nail', 'hammer', 'screw']}
  • 42. Access >>> box['size'] # must retrieve on key that exists {'width': 20, 'height': 10} >>> box['size']['width'] 20 >>> box['contents'] ['nail', 'hammer', 'screw'] >>> box['contents'][-1] 'screw'
  • 43. Access >>> box.hasKey('size') True >>> box.items() # do it only on small dictionaries [('color', 'red'), ('isCardboard', True), ('contents', ['nail', 'hammer', 'screw']), ('size', {'width': 20, 'height': 10})] >>> box.items()[0] ('color', 'red') >>> box.items()[0][-1] 'red'
  • 44. Adding Key-Value Pairs ● You can add new key value pairs to the previously created dictionary my_dict = {} for c in 'abcdefg': my_dict[c.upper()] = c >>> my_dict {'A': 'a', 'C': 'c', 'B': 'b', 'E': 'e', 'D': 'd', 'G': 'g', 'F': 'f'} >>> my_dict[(1, 2)] = [1, 2] >>> my_dict[(1, 2)] [1, 2]
  • 45. Construction ● The constructor dict() can be used to create dictionaries from a sequence of two-item sequences >>> my_dict2 = dict([['A', 'a'], ['B', 'b'], ['C', 'c']]) >>> my_dict2 {'A': 'a', 'C': 'c', 'B': 'b'} >>> my_dict3 = dict([('A', 'a'), ('B', 'b'), ('C', 'c')]) >>> my_dict3 {'A': 'a', 'C': 'c', 'B': 'b'} >>> my_dict4 = dict((('A', 'a'), ('B', 'b'), ('C', 'c'))) >>> my_dict4 {'A': 'a', 'C': 'c', 'B': 'b'}
  • 46. Construction ● ● ● The constructor dict() can be used to create dictionaries from keyword-value pairs The keyword-value pair has the following syntax: keyword = value Keywords are converted into strings >>> my_dict5 = dict(first_name = "John", last_name = "Nicholson") >>> my_dict5 {'first_name': 'John', 'last_name': 'Nicholson'}
  • 47. Checking for Keys ● Option 1: key in dictionary >>> my_dict = dict(first_name = "John", last_name = "Nicholson") >>> "first_name" in my_dict True >>> "middle_name" not in my_dict True ● Option 2: dictionary.has_key(<key>) >>> my_dict.has_key('first_name') True
  • 48. Safe Access with get() ● dict.get() is similar to use dict[] but safer ● Syntax: dict.get(key[, default]) ● ● ● dict[key] returns the value of key in dict or throws error if key is not in dict dict.get(key) returns value of key in dict or None if key is not in dict dict.get(key, default) returns value of key in dict or default if key is not in dict
  • 49. Example >>> my_dict = {'one' : 1, 'two' : ['a', 'b', 'c']} >>> my_dict['one'] 1 >>> my_dict['three'] ## error >>> my_dict.get('three') ## None (nothing) returned >>> my_dict.get('three', 'not in dict') 'not in dict' ## default 'not in dict' returned
  • 50. Clearing Dictionaries >>> my_dict = { } >>> my_dict['one'] = [1, 2, 3] >>> my_dict['two'] = ['a', 'b', 'c'] >>> my_dict {'two': ['a', 'b', 'c'], 'one': [1, 2, 3]} >>> my_dict.clear() >>> my_dict {}
  • 51. Shallow Copying ● The method copy() returns a shallow copy of the dictionary my_dict = {'one' : 1, 'two' : ['a', 'b', 'c']} my_dict2 = my_dict.copy() print 'shallow copying:', my_dict, my_dict2 del my_dict2['two'][-1] print 'shallow copying:', my_dict, my_dict2 Output: shallow copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b', 'c'], 'one': 1} shallow copying: {'two': ['a', 'b'], 'one': 1} {'two': ['a', 'b'], 'one': 1}
  • 52. Deep Copying ● The method deepcopy() returns a deep copy of the dictionary from copy import deepcopy my_dict3 = {'one' : 1, 'two' : ['a', 'b', 'c']} my_dict4 = deepcopy(my_dict3) print 'deep copying:', my_dict3, my_dict4 del my_dict4['two'][-1] print 'deep copying:', my_dict3, my_dict4 Output: deep copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b', 'c'], 'one': 1} deep copying: {'two': ['a', 'b', 'c'], 'one': 1} {'two': ['a', 'b'], 'one': 1}
  • 53. Dictionary Creation From Keys ● The method fromkeys() creates a dictionary from keys each of which maps to None >>> d = {}.fromkeys(['key1', 'key2']) >>> d {'key2': None, 'key1': None} >>> d['key1'] = 'value1' >>> d['key2'] = 'value2' >>> d {'key2': 'value2', 'key1': 'value1'}
  • 54. Deleting Keys with del() ● You can use del() to delete key-value pairs from dictionaries >>> my_dict {0: 0, 1: 1, 2: 4, 3: 9} >>> del my_dict[2] >>> my_dict {0: 0, 1: 1, 3: 9}
  • 55. Reading & References ● ● ● www.python.org Ch 03 (Strings), M. L. Hetland. Beginning Python From nd Novice to Professional, 2 Ed., APRESS Ch 05 (Object Comparison, Loops), M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS