SlideShare a Scribd company logo
Functional Programming 
in Python 
Reuven M. Lerner, PhD • reuven@lerner.co.il 
October 22nd, 2014
Who am I? 
• Programmer, consultant, developer, trainer 
• Long-time Python (+Ruby) user 
• Linux Journal columnist 
• Author Practice Makes Python! 
• PhD in Learning Sciences from Northwestern 
• Read (lots) more at http://lerner.co.il/ 
2
Functional programming 
• A different way of thinking about programming 
• A different way of writing programs 
• A different way of approaching problems 
• Often provides new, clean, elegant solutions… 
• … but again, it requires that you think about things 
very differently. 
4
5 
Input 
Function 
Output 
No external state 
changes in this function… 
… and if you can avoid 
internal state, even better!
Why work this way? 
• Simpler functions — easier to write and maintain 
• Easer to test functions, and predict their results 
• Easier to combine functions in new, different ways 
• You can split work across threads, processors, or 
even machines without any ill effects 
• Certain things can be expressed easily, elegantly 
6
The FP perspective 
Input f1 f2 f3 f4 f5 Output 
7
OO or functional? 
• Python supports both styles 
• It’s common to mix them in one program 
• My current approach: Use objects in general, but 
functional techniques inside of methods 
8
Sequences and iterables 
• There are three built-in sequences in Python: 
strings, tuples, and lists 
• Many other objects are "iterable," meaning that you 
can stick them into a "for" loop and get one item at 
a time 
• Examples: files and dicts 
• This discussion mainly has to do with iterables 
9
Where are iterables? 
• Strings, lists, and tuples (obviously) 
• Dicts, sets, and files 
• Complex data structures: Lists of lists, lists of dicts, 
dicts of dicts (and others) 
• Results from database queries 
• Information from a network feed 
• Many, many objects return iterables 
10
Transformation 
• You often want to turn one iterable into another 
• For example, you might want to turn the list 
[0,1,2,3,4] # range(5) 
• into the list 
[0,1,4,9,16] 
• We can transform the first list into the other by 
applying a Python function. 
11
Each list 
item 
def square(x): 
return x*x 
New list 
item 
12
The usual solution 
>>>> input = range(5) 
>>>> def square(x): 
return x*x 
>>> output = [ ] 
>>> for x in input: 
output.append(square(x)) 
>>> output 
[0, 1, 4, 9, 16] 
13
What's wrong with this? 
• Nothing is wrong. 
• But functional programming looks at this, and says: 
• Why create a new variable ("output")? 
• Why are you building it, one step at a time? 
• Why are you modifying the state of "output"? 
• Why do it in such a clumsy way? 
14
The elegant way 
"I want to apply my function, square, to each and 
every element of the input list, and get a list back." 
15
Input list 
def square(x): 
return x*x 
Output list 
16
List comprehensions 
• In Python, we do this with a "list comprehension": 
[square(x) for x in range(5)] 
• Or if you prefer: 
[x*x for x in range(5)] 
17
Ints to strings 
• I can't say 
', '.join(range(5)) 
• because str.join's input must contain strings. 
• Solution: 
', '.join([str(x) for x in range(5)]) 
18
Lowercase all words 
• I can transform a sentence into all lowercase: 
words = 'This is a sentence for my Python 
class'.split() 
[word.lower() for word in words] 
• Or even: 
' '.join([word.lower() for word in words]) 
19
Filenames to files 
• I can get a list of filenames from os.listdir: 
os.listdir('/etc') 
• I can get a file object for each of these: 
[open('/etc/' + filename) 
for filename in os.listdir('/etc')] 
20
File contents 
• If I want to get the names of users on my Unix 
system, I can say 
[ line.split(":")[0] 
for line in open('/etc/passwd') ] 
21
Filtering 
• If I want to get the names of users on my Unix 
system, I can say 
[ line.split(":")[0] 
for line in open('/etc/passwd') 
if line[0] != '#' ] 
22
Pig Latin! 
def plword(word): 
vowels = 'aeiou' 
if word[0] in vowels: 
return word + 'way' 
else: 
return word[1:] + word[0] + 'ay' 
23
Translation 
' '.join([plword(word) 
for word in open('column-215') ]) 
24
Bottom line 
• Comprehensions are Python's answer to the 
traditional functions "map" and "filter". 
• Once you start to think in terms of "mapping" one 
sequence to another, you'll see this pattern 
everywhere. 
• You'll reduce the number of assignments you make. 
Your programs will be shorter and easier to 
understand. And you'll be able to stack these 
manipulations, without worrying about side effects. 
25
Functions 
• Where are the functions in functional programming? 
• Let's write some functions! Let's use some 
functions! 
26
Calling functions 
• We call functions in Python with () 
• No parentheses — no function call! 
x = len('abc') 
type(x) 
int 
x = len 
type(x) 
builtin_function_or_method 
27
Parentheses 
• In Python, something that can be executed with 
parentheses is known as "callable". 
• 'a'() will result in an error, that a string isn't 
"callable." 
• Normally, we say that functions and classes are 
callable. How do we know? They have a __call__ 
attribute! 
28
Dispatch table 
def foo(): return "foo" 
def bar(): return "bar" 
d = {'foo':foo, 'bar':bar} 
29
Sorting 
• We know that we can use list.sort to sort a list: 
words= 'This is a sentence for my online 
Python class'.split() 
words.sort() 
30
Changing sort's behavior 
• The optional "key" parameter lets you pass a 
function that changes sort's behavior 
• Define a function, and pass it to "key". 
• Or use an existing function: 
words.sort(key=str.lower) 
words.sort(key=len) 
31
The real lesson: 
You can do it, too! 
• Take a function as a parameter 
• Invoke the function within your function 
• Now you have a more generic function, whose 
behavior can be modified! 
32
Function 
Use 
input 2 
33 
Input 1 
Output 
input 2
Example 
• Let's implement transform_values! 
>>> d = {'a':1, 'b':2, 'c':3} 
>>> transform_values(lambda x: x*x, d) 
{'a': 1, 'b': 4, 'c': 9} 
34
Summary 
• Functions are data, too! Treating them as such 
makes your programs more flexible, generic, and 
easy to understand 
• Python's comprehensions are a modern version of 
classic "map" and "filter" functions. 
• Composing functions isn't the only solution, but it's 
a really flexible and useful one 
• It becomes easier with practice! 
35
Questions? Comments? 
And remember… 
• Early-bird discount on my book! 
• http://lerner.co.il/practice-makes-python 
• Use the WEBINAR coupon code for 10% off! 
• Courses are at http://lerner.co.il/courses 
• Contact me: reuven@lerner.co.il 
• Follow me: @reuvenmlerner 
36

More Related Content

What's hot

Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with Javascript
Doug Sparling
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
Assaf Gannon
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
Jagdish Chavan
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
Svetlin Nakov
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
newmedio
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Shakti Singh Rathore
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
Assaf Gannon
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 

What's hot (19)

Functions in python
Functions in pythonFunctions in python
Functions in python
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with Javascript
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function C++
Function C++ Function C++
Function C++
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 

Viewers also liked

Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friend
Reuven Lerner
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
Reuven Lerner
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?
Reuven Lerner
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
Reuven Lerner
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL database
Reuven Lerner
 
Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.key
Reuven Lerner
 
2013 State of Cloud Survey SMB Results
2013 State of Cloud Survey SMB Results2013 State of Cloud Survey SMB Results
2013 State of Cloud Survey SMB Results
Symantec
 
Breaking through the Clouds
Breaking through the CloudsBreaking through the Clouds
Breaking through the Clouds
Andy Piper
 
2013 Future of Cloud Computing - 3rd Annual Survey Results
2013 Future of Cloud Computing - 3rd Annual Survey Results2013 Future of Cloud Computing - 3rd Annual Survey Results
2013 Future of Cloud Computing - 3rd Annual Survey Results
Michael Skok
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Reuven Lerner
 
Can we hack open source #cloud platforms to help reduce emissions?
Can we hack open source #cloud platforms to help reduce emissions?Can we hack open source #cloud platforms to help reduce emissions?
Can we hack open source #cloud platforms to help reduce emissions?
Tom Raftery
 
Summer School Scale Cloud Across the Enterprise
Summer School   Scale Cloud Across the EnterpriseSummer School   Scale Cloud Across the Enterprise
Summer School Scale Cloud Across the Enterprise
WSO2
 
Simplifying The Cloud Top 10 Questions By SMBs
Simplifying The Cloud Top 10 Questions By SMBsSimplifying The Cloud Top 10 Questions By SMBs
Simplifying The Cloud Top 10 Questions By SMBs
Sun Digital, Inc.
 
Penetrating the Cloud: Opportunities & Challenges for Businesses
Penetrating the Cloud: Opportunities & Challenges for BusinessesPenetrating the Cloud: Opportunities & Challenges for Businesses
Penetrating the Cloud: Opportunities & Challenges for Businesses
CompTIA
 
The Inevitable Cloud Outage
The Inevitable Cloud OutageThe Inevitable Cloud Outage
The Inevitable Cloud Outage
Newvewm
 
Avoiding Cloud Outage
Avoiding Cloud OutageAvoiding Cloud Outage
Avoiding Cloud Outage
Nati Shalom
 
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud ComputingLinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
Mark Hinkle
 
Delivering IaaS with Open Source Software
Delivering IaaS with Open Source SoftwareDelivering IaaS with Open Source Software
Delivering IaaS with Open Source Software
Mark Hinkle
 
Linthicum what is-the-true-future-of-cloud-computing
Linthicum what is-the-true-future-of-cloud-computingLinthicum what is-the-true-future-of-cloud-computing
Linthicum what is-the-true-future-of-cloud-computing
David Linthicum
 
Best Practices for Architecting in the Cloud - Jeff Barr
Best Practices for Architecting in the Cloud - Jeff BarrBest Practices for Architecting in the Cloud - Jeff Barr
Best Practices for Architecting in the Cloud - Jeff Barr
Amazon Web Services
 

Viewers also liked (20)

Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friend
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL database
 
Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.key
 
2013 State of Cloud Survey SMB Results
2013 State of Cloud Survey SMB Results2013 State of Cloud Survey SMB Results
2013 State of Cloud Survey SMB Results
 
Breaking through the Clouds
Breaking through the CloudsBreaking through the Clouds
Breaking through the Clouds
 
2013 Future of Cloud Computing - 3rd Annual Survey Results
2013 Future of Cloud Computing - 3rd Annual Survey Results2013 Future of Cloud Computing - 3rd Annual Survey Results
2013 Future of Cloud Computing - 3rd Annual Survey Results
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, Jerusalem
 
Can we hack open source #cloud platforms to help reduce emissions?
Can we hack open source #cloud platforms to help reduce emissions?Can we hack open source #cloud platforms to help reduce emissions?
Can we hack open source #cloud platforms to help reduce emissions?
 
Summer School Scale Cloud Across the Enterprise
Summer School   Scale Cloud Across the EnterpriseSummer School   Scale Cloud Across the Enterprise
Summer School Scale Cloud Across the Enterprise
 
Simplifying The Cloud Top 10 Questions By SMBs
Simplifying The Cloud Top 10 Questions By SMBsSimplifying The Cloud Top 10 Questions By SMBs
Simplifying The Cloud Top 10 Questions By SMBs
 
Penetrating the Cloud: Opportunities & Challenges for Businesses
Penetrating the Cloud: Opportunities & Challenges for BusinessesPenetrating the Cloud: Opportunities & Challenges for Businesses
Penetrating the Cloud: Opportunities & Challenges for Businesses
 
The Inevitable Cloud Outage
The Inevitable Cloud OutageThe Inevitable Cloud Outage
The Inevitable Cloud Outage
 
Avoiding Cloud Outage
Avoiding Cloud OutageAvoiding Cloud Outage
Avoiding Cloud Outage
 
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud ComputingLinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
LinuxFest NW 2013: Hitchhiker's Guide to Open Source Cloud Computing
 
Delivering IaaS with Open Source Software
Delivering IaaS with Open Source SoftwareDelivering IaaS with Open Source Software
Delivering IaaS with Open Source Software
 
Linthicum what is-the-true-future-of-cloud-computing
Linthicum what is-the-true-future-of-cloud-computingLinthicum what is-the-true-future-of-cloud-computing
Linthicum what is-the-true-future-of-cloud-computing
 
Best Practices for Architecting in the Cloud - Jeff Barr
Best Practices for Architecting in the Cloud - Jeff BarrBest Practices for Architecting in the Cloud - Jeff Barr
Best Practices for Architecting in the Cloud - Jeff Barr
 

Similar to Functional Python Webinar from October 22nd, 2014

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Web Development Bootcamp - Python session
Web Development Bootcamp - Python sessionWeb Development Bootcamp - Python session
Web Development Bootcamp - Python session
Amir Shokri
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
Chiyoung Song
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
PranavSB
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitrWiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
Ann Loraine
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
 
Pa1 session 2
Pa1 session 2 Pa1 session 2
Pa1 session 2
aiclub_slides
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 

Similar to Functional Python Webinar from October 22nd, 2014 (20)

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Web Development Bootcamp - Python session
Web Development Bootcamp - Python sessionWeb Development Bootcamp - Python session
Web Development Bootcamp - Python session
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
Python ppt
Python pptPython ppt
Python ppt
 
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitrWiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
WiNGS 2014 Workshop 2 R, RStudio, and reproducible research with knitr
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
Pa1 session 2
Pa1 session 2 Pa1 session 2
Pa1 session 2
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 

More from Reuven Lerner

Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of software
Reuven Lerner
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
Reuven Lerner
 
Rails traps
Rails trapsRails traps
Rails traps
Reuven Lerner
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Reuven Lerner
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
Reuven Lerner
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in Israel
Reuven Lerner
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
Reuven Lerner
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Reuven Lerner
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
Reuven Lerner
 
ActiveRecord 2.3
ActiveRecord 2.3ActiveRecord 2.3
ActiveRecord 2.3
Reuven Lerner
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
Reuven Lerner
 
Rails console
Rails consoleRails console
Rails console
Reuven Lerner
 
Rails tools
Rails toolsRails tools
Rails tools
Reuven Lerner
 
Why ruby and rails
Why ruby and railsWhy ruby and rails
Why ruby and rails
Reuven Lerner
 

More from Reuven Lerner (14)

Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of software
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Rails traps
Rails trapsRails traps
Rails traps
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in Israel
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
 
ActiveRecord 2.3
ActiveRecord 2.3ActiveRecord 2.3
ActiveRecord 2.3
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
Rails console
Rails consoleRails console
Rails console
 
Rails tools
Rails toolsRails tools
Rails tools
 
Why ruby and rails
Why ruby and railsWhy ruby and rails
Why ruby and rails
 

Recently uploaded

14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
anfaltahir1010
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 

Recently uploaded (20)

14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLESINTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
INTRODUCTION TO AI CLASSICAL THEORY TARGETED EXAMPLES
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 

Functional Python Webinar from October 22nd, 2014

  • 1. Functional Programming in Python Reuven M. Lerner, PhD • reuven@lerner.co.il October 22nd, 2014
  • 2. Who am I? • Programmer, consultant, developer, trainer • Long-time Python (+Ruby) user • Linux Journal columnist • Author Practice Makes Python! • PhD in Learning Sciences from Northwestern • Read (lots) more at http://lerner.co.il/ 2
  • 3.
  • 4. Functional programming • A different way of thinking about programming • A different way of writing programs • A different way of approaching problems • Often provides new, clean, elegant solutions… • … but again, it requires that you think about things very differently. 4
  • 5. 5 Input Function Output No external state changes in this function… … and if you can avoid internal state, even better!
  • 6. Why work this way? • Simpler functions — easier to write and maintain • Easer to test functions, and predict their results • Easier to combine functions in new, different ways • You can split work across threads, processors, or even machines without any ill effects • Certain things can be expressed easily, elegantly 6
  • 7. The FP perspective Input f1 f2 f3 f4 f5 Output 7
  • 8. OO or functional? • Python supports both styles • It’s common to mix them in one program • My current approach: Use objects in general, but functional techniques inside of methods 8
  • 9. Sequences and iterables • There are three built-in sequences in Python: strings, tuples, and lists • Many other objects are "iterable," meaning that you can stick them into a "for" loop and get one item at a time • Examples: files and dicts • This discussion mainly has to do with iterables 9
  • 10. Where are iterables? • Strings, lists, and tuples (obviously) • Dicts, sets, and files • Complex data structures: Lists of lists, lists of dicts, dicts of dicts (and others) • Results from database queries • Information from a network feed • Many, many objects return iterables 10
  • 11. Transformation • You often want to turn one iterable into another • For example, you might want to turn the list [0,1,2,3,4] # range(5) • into the list [0,1,4,9,16] • We can transform the first list into the other by applying a Python function. 11
  • 12. Each list item def square(x): return x*x New list item 12
  • 13. The usual solution >>>> input = range(5) >>>> def square(x): return x*x >>> output = [ ] >>> for x in input: output.append(square(x)) >>> output [0, 1, 4, 9, 16] 13
  • 14. What's wrong with this? • Nothing is wrong. • But functional programming looks at this, and says: • Why create a new variable ("output")? • Why are you building it, one step at a time? • Why are you modifying the state of "output"? • Why do it in such a clumsy way? 14
  • 15. The elegant way "I want to apply my function, square, to each and every element of the input list, and get a list back." 15
  • 16. Input list def square(x): return x*x Output list 16
  • 17. List comprehensions • In Python, we do this with a "list comprehension": [square(x) for x in range(5)] • Or if you prefer: [x*x for x in range(5)] 17
  • 18. Ints to strings • I can't say ', '.join(range(5)) • because str.join's input must contain strings. • Solution: ', '.join([str(x) for x in range(5)]) 18
  • 19. Lowercase all words • I can transform a sentence into all lowercase: words = 'This is a sentence for my Python class'.split() [word.lower() for word in words] • Or even: ' '.join([word.lower() for word in words]) 19
  • 20. Filenames to files • I can get a list of filenames from os.listdir: os.listdir('/etc') • I can get a file object for each of these: [open('/etc/' + filename) for filename in os.listdir('/etc')] 20
  • 21. File contents • If I want to get the names of users on my Unix system, I can say [ line.split(":")[0] for line in open('/etc/passwd') ] 21
  • 22. Filtering • If I want to get the names of users on my Unix system, I can say [ line.split(":")[0] for line in open('/etc/passwd') if line[0] != '#' ] 22
  • 23. Pig Latin! def plword(word): vowels = 'aeiou' if word[0] in vowels: return word + 'way' else: return word[1:] + word[0] + 'ay' 23
  • 24. Translation ' '.join([plword(word) for word in open('column-215') ]) 24
  • 25. Bottom line • Comprehensions are Python's answer to the traditional functions "map" and "filter". • Once you start to think in terms of "mapping" one sequence to another, you'll see this pattern everywhere. • You'll reduce the number of assignments you make. Your programs will be shorter and easier to understand. And you'll be able to stack these manipulations, without worrying about side effects. 25
  • 26. Functions • Where are the functions in functional programming? • Let's write some functions! Let's use some functions! 26
  • 27. Calling functions • We call functions in Python with () • No parentheses — no function call! x = len('abc') type(x) int x = len type(x) builtin_function_or_method 27
  • 28. Parentheses • In Python, something that can be executed with parentheses is known as "callable". • 'a'() will result in an error, that a string isn't "callable." • Normally, we say that functions and classes are callable. How do we know? They have a __call__ attribute! 28
  • 29. Dispatch table def foo(): return "foo" def bar(): return "bar" d = {'foo':foo, 'bar':bar} 29
  • 30. Sorting • We know that we can use list.sort to sort a list: words= 'This is a sentence for my online Python class'.split() words.sort() 30
  • 31. Changing sort's behavior • The optional "key" parameter lets you pass a function that changes sort's behavior • Define a function, and pass it to "key". • Or use an existing function: words.sort(key=str.lower) words.sort(key=len) 31
  • 32. The real lesson: You can do it, too! • Take a function as a parameter • Invoke the function within your function • Now you have a more generic function, whose behavior can be modified! 32
  • 33. Function Use input 2 33 Input 1 Output input 2
  • 34. Example • Let's implement transform_values! >>> d = {'a':1, 'b':2, 'c':3} >>> transform_values(lambda x: x*x, d) {'a': 1, 'b': 4, 'c': 9} 34
  • 35. Summary • Functions are data, too! Treating them as such makes your programs more flexible, generic, and easy to understand • Python's comprehensions are a modern version of classic "map" and "filter" functions. • Composing functions isn't the only solution, but it's a really flexible and useful one • It becomes easier with practice! 35
  • 36. Questions? Comments? And remember… • Early-bird discount on my book! • http://lerner.co.il/practice-makes-python • Use the WEBINAR coupon code for 10% off! • Courses are at http://lerner.co.il/courses • Contact me: reuven@lerner.co.il • Follow me: @reuvenmlerner 36