PYTHON DATA SCIENCE TOOLBOX II. List comprehensions

Similar documents
CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

[301] JSON. Tyler Caraza-Harter

Iterators & Generators

CSCI 1101B. While Loops

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

G. Tardiani RoboCup Rescue. EV3 Workshop Part 1 Introduction to RobotC

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018

CS 234 Python Review Part 2

Decision Making in C

Working with Lists 4

Introduction. C provides two styles of flow control:

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015

More on Lists, Dictionaries Introduction to File I/O CS 8: Introduction to Computer Science Lecture #10

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Notebook. March 30, 2019

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

CMSC 201 Fall 2018 Python Coding Standards

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

peval Documentation Release Bogdan Opanchuk

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Cambridge International Examinations Cambridge International Advanced Subsidiary and Advanced Level. Published

Python Programming. Introduction Part II

DSC 201: Data Analysis & Visualization

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Lists, loops and decisions

LECTURE 3 Python Basics Part 2

Extending Jython. with SIM, SPARQL and SQL

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

COMPUTER PROGRAMMING LOOPS

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Python: Functions and Generators. Giuseppe Attardi

Python Lists and Dictionaries CS 8: Introduction to Computer Science, Winter 2019 Lecture #13

Lessons on Python Functions

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Comp Exam 1 Overview.

Real Python: Python 3 Cheat Sheet

QUark Language Reference Manual

CS 331/401 Summer 2018 Midterm Exam

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Ruby: Introduction, Basics

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Expressions vs statements

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

CMSC201 Computer Science I for Majors

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Chapter 2, Part III Arithmetic Operators and Decision Making

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

Basic Syntax - First Program 1

OOP and Scripting in Python Advanced Features

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Module 10: Imperative Programming, Modularization, and The Future

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Introduction to Python

CMSC 201 Spring 2018

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS1 Lecture 22 Mar. 6, 2019

Table of Contents EVALUATION COPY

G Programming Languages - Fall 2012

DATA 301 Introduction to Data Analytics Python. Dr. Ramon Lawrence University of British Columbia Okanagan

Language Proposal: tail

CSI33 Data Structures

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Introduction to Python - Part I CNV Lab

CIS192 Python Programming

Quiz 1: Functions and Procedures

Basic Python 3 Programming (Theory & Practical)

In this lab, you will learn more about selection statements. You will get familiar to

ARTIFICIAL INTELLIGENCE AND PYTHON

CIS192 Python Programming

C++ for Python Programmers

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

IAP Python - Lecture 2

Introduction to: Computers & Programming:

Control Structures 1 / 17

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Introduction to Python programming, II

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

CSC148 Week 2. Larry Zhang

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CP215 Application Design

Starting chapter 5. l First open file, and say purpose read or write inputfile = open('mydata.txt', 'r') outputfile = open('myresults.

APCS Semester #1 Final Exam Practice Problems

Using Scala in CS241

Kyle Rainville Littleton Coin Company

Selection Statement ( if )

Scope and Parameter Passing 1 / 19

Functional Programming

Transcription:

PYTHON DATA SCIENCE TOOLBOX II List comprehensions

Populate a list with a for loop In [1]: nums = [12, 8, 21, 3, 16] In [2]: new_nums = [] In [3]: for num in nums:...: new_nums.append(num + 1) In [4]: print(new_nums) [13, 9, 22, 4, 17]

A list comprehension In [1]: nums = [12, 8, 21, 3, 16] In [2]: new_nums = [num + 1 for num in nums] In [3]: print(new_nums) [13, 9, 22, 4, 17]

For loop and list comprehension syntax In [1]: new_nums = [num + 1 for num in nums] In [2]: for num in nums:...: new_nums.append(num + 1) In [3]: print(new_nums) [13, 9, 22, 4, 17]

List comprehension with range() In [1]: result = [num for num in range(11)] In [2]: print(result) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List comprehensions Collapse for loops for building lists into a single line Components Iterable Iterator variable (represent members of iterable) Output expression

Nested loops (1) In [1]: pairs_1 = [] In [2]: for num1 in range(0, 2):...: for num2 in range(6, 8):...: pairs_1.append(num1, num2) In [3]: print(pairs_1) [(0, 6), (0, 7), (1, 6), (1, 7)] How to do this with a list comprehension?

Nested loops (2) In [1]: pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, 8)] In [2]: print(pairs_2) [(0, 6), (0, 7), (1, 6), (1, 7)] Tradeoff: readability

PYTHON DATA SCIENCE TOOLBOX II Let s practice!

PYTHON DATA SCIENCE TOOLBOX II Advanced comprehensions

Conditionals in comprehensions Conditionals on the iterable In [1]: [num ** 2 for num in range(10) if num % 2 == 0] Out[1]: [0, 4, 16, 36, 64] Python documentation on the % operator: In [1]: 5 % 2 Out[1]: 1 In [2]: 6 % 2 Out[2]: 0

Conditionals in comprehensions Conditionals on the output expression In [2]: [num ** 2 if num % 2 == 0 else 0 for num in range(10)] Out[2]: [0, 0, 4, 0, 16, 0, 36, 0, 64, 0]

Dict comprehensions Create dictionaries Use curly braces {} instead of brackets [] In [1]: pos_neg = {num: -num for num in range(9)} In [2]: print(pos_neg) {0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8} In [3]: print(type(pos_neg)) <class 'dict'>

PYTHON DATA SCIENCE TOOLBOX II Let s practice!

PYTHON DATA SCIENCE TOOLBOX II Introduction to generators

Generator expressions Recall list comprehension In [1]: [2 * num for num in range(10)] Out[1]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Use ( ) instead of [ ] In [2]: (2 * num for num in range(10)) Out[2]: <generator object <genexpr> at 0x1046bf888>

List comprehensions vs. generators List comprehension - returns a list Generators - returns a generator object Both can be iterated over

Printing values from generators (1) In [1]: result = (num for num in range(6)) In [2]: for num in result:...: print(num) 0 1 2 3 4 5 In [1]: result = (num for num in range(6)) In [2]: print(list(result)) [0, 1, 2, 3, 4, 5]

Printing values from generators (2) In [1]: result = (num for num in range(6)) In [2]: print(next(result)) 0 Lazy evaluation In [3]: print(next(result)) 1 In [4]: print(next(result)) 2 In [5]: print(next(result)) 3 In [6]: print(next(result)) 4

Generators vs list comprehensions Python Data Science Toolbox II

Generators vs list comprehensions Python Data Science Toolbox II

Conditionals in generator expressions In [1]: even_nums = (num for num in range(10) if num % 2 == 0) In [2]: print(list(even_nums)) [0, 2, 4, 6, 8]

Generator functions Produces generator objects when called Defined like a regular function - def Yields a sequence of values instead of returning a single value Generates a value with yield keyword

Build a generator function sequence.py def num_sequence(n): """Generate values from 0 to n.""" i = 0 while i < n: yield i i += 1

Use a generator function In [1]: result = num_sequence(5) In [2]: print(type(result)) <class 'generator'> In [3]: for item in result:...: print(item) 0 1 2 3 4

PYTHON DATA SCIENCE TOOLBOX II Let s practice!

PYTHON DATA SCIENCE TOOLBOX II Wrap-up: comprehensions

Re-cap: list comprehensions Basic [output expression for iterator variable in iterable] Advanced [output expression + conditional on output for iterator variable in iterable + conditional on iterable]

PYTHON DATA SCIENCE TOOLBOX II Let s practice!