List Comprehensions. Python’s higher-order functions  Python supports higher-order functions that operate on lists similar to Scheme’s >>> def square(x):

Slides:



Advertisements
Similar presentations
Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
Advertisements

Container Types in Python
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Python 2 Some material adapted from Upenn cis391 slides and other sources.
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
Foundations of Programming Languages: Introduction to Lambda Calculus
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
1 Predicates and quantifiers Chapter 8 Formal Specification using Z.
Algorithms. Introduction Before writing a program: –Have a thorough understanding of the problem –Carefully plan an approach for solving it While writing.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Introduction to Python II CIS 391: Artificial Intelligence Fall, 2008.
Dr. Muhammed Al-Mulhem ICS An Introduction to Functional Programming.
Introduction to Python II CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Python Control of Flow.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Decision Structures and Boolean Logic
CS1022 Computer Programming & Principles Lecture 1.2 A brief introduction to Python.
The College of Saint Rose CIS 433 – Programming Languages David Goldschmidt, Ph.D. from Concepts of Programming Languages, 9th edition by Robert W. Sebesta,
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Python functional programming. Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values.
E - BOOK FOR COLLEGE ALGEBRA King Fahd University of Petroleum & Minerals 2.3 E - BOOK FOR COLLEGE ALGEBRA King Fahd University of Petroleum & Minerals.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Section 2.7 Solving Inequalities. Objectives Determine whether a number is a solution of an inequality Graph solution sets and use interval notation Solve.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
1-1 An Introduction to Functional Programming Sept
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
CSE 425: Functional Programming I Programs as Functions Some programs act like mathematical functions –Associate a set of input values from the function’s.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Processing of Collections (Advanced) 6.0.
Control Structures I Chapter 3
Higher Order Functions
Functional Programming
Introduction to Higher Order (Functional Programming) (Python) part 2
CS1022 Computer Programming & Principles
Theory of Computation Lecture 4: Programs and Computable Functions II
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Functions (Notation and Evaluating)
Topics The if Statement The if-else Statement Comparing Strings
Functional Processing of Collections (Advanced)
CHAPTER FOUR Functions.
Topics The if Statement The if-else Statement Comparing Strings
Python 2 Some material adapted from Upenn cis391 slides and other sources.
A First Book of ANSI C Fourth Edition
FP Foundations, Scheme In Text: Chapter 14.
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Functions (Notation and Evaluating)
Programming Techniques
(more) Python.
CS2011 Introduction to Programming I Selections (I)
Java Programming Loops
Stream.
Functional Programming
functions are also data! other functions as input!
CMPU-145: Foundations of Computer Science Spring, 2019
Presentation transcript:

List Comprehensions

Python’s higher-order functions  Python supports higher-order functions that operate on lists similar to Scheme’s >>> def square(x): return x*x >>> def even(x): return 0 == x % 2 >>> map(square, range(10,20)) [100, 121, 144, 169, 196, 225, 256, 289, 324, 361] >>> filter(even, range(10,20)) [10, 12, 14, 16, 18] >>> map(square, filter(even, range(10,20))) [100, 144, 196, 256, 324]  But many Python programmers prefer to use list comprehensions, instead

List Comprehensions  A list comprehension is a programming language construct for creating a list based on existing lists Haskell, Erlang, Scala and Python have them  Why “comprehension”? The term is borrowed from math’s set comprehension notation for defining sets in terms of other sets  A powerful and popular feature in Python Generate a new list by applying a function to every member of an original list  Python’s notation: [ expression for name in list ]

List Comprehensions  The syntax of a list comprehension is somewhat tricky [x-10 for x in grades if x>0 ]  Syntax suggests that of a for-loop, an in operation, or an if statement  All three of these keywords (‘for’, ‘in’, and ‘if’) are also used in the syntax of forms of list comprehensions [ expression for name in list ]

List Comprehensions >>> li = [3, 6, 2, 7] >>> [elem*2 for elem in li] [6, 12, 4, 14] [ expression for name in list ] Where expression is some calculation or operation acting upon the variable name. For each member of the list, the list comprehension 1. sets name equal to that member, 2.calculates a new value using expression, It then collects these new values into a list which is the return value of the list comprehension. Note: Non-standard colors on next few slides clarify the list comprehension syntax. [ expression for name in list ]

List Comprehensions  If list contains elements of different types, then expression must operate correctly on the types of all of list members.  If the elements of list are other containers, then name can consist of a container of names matching the type and “shape” of the list members. >>> li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)] >>> [ n * 3 for (x, n) in li] [3, 6, 21]  Containers are objects that contain references to other objects (e.g., lists, types, dictionaries) [ expression for name in list ]

 expression can also contain user-defined functions. >>> def subtract(a, b): return a – b >>> oplist = [(6, 3), (1, 7), (5, 5)] >>> [subtract(y, x) for (x, y) in oplist] [-3, 6, 0] List Comprehensions [ expression for name in list ]

Syntactic sugar List comprehensions can be viewed as syntactic sugar for a typical higher-order functions [ expression for name in list ] map( lambda name: expression, list ) [ 2*x+1 for x in [10, 20, 30] ] map( lambda x: 2*x+1, [10, 20, 30] )

Filtered List Comprehension  Filter determines whether expression is performed on each member of the list.  For each element of list, checks if it satisfies the filter condition.  If the filter condition returns False, that element is omitted from the list before the list comprehension is evaluated. [ expression for name in list if filter ]

>>> li = [3, 6, 2, 7, 1, 9] >>> [elem*2 for elem in li if elem > 4] [12, 14, 18]  Only 6, 7, and 9 satisfy the filter condition  So, only 12, 14, and 18 are produce. Filtered List Comprehension [ expression for name in list if filter ]

More syntactic sugar Including an if clause begins to show the benefits of the sweetened form [ expression for name in list if filt ] map( lambda name. expression, filter(filt, list) ) [ 2*x+1 for x in [10, 20, 30] if x > 0 ] map( lambda x: 2*x+1, filter( lambda x: x > 0, [10, 20, 30] )

 Since list comprehensions take a list as input and produce a list as output, they are easily nested >>> li = [3, 2, 4, 1] >>> [elem*2 for elem in [item+1 for item in li] ] [8, 6, 10, 4]  The inner comprehension produces: [4, 3, 5, 2]  So, the outer one produces: [8, 6, 10, 4] Nested List Comprehensions [ expression for name in list ]

Syntactic sugar [ e1 for n1 in [ e1 for n1 list ] ] map( lambda n1: e1, map( lambda n2: e2, list ) ) [2*x+1 for x in [y*y for y in [10, 20, 30]]] map( lambda x: 2*x+1, map( lambda y: y*y, [10, 20, 30] ))