List comprehensions (and other shortcuts) UW CSE 160 Winter 2016.

Slides:



Advertisements
Similar presentations
List comprehensions UW CSE 140 Winter Ways to express a list 1.Explicitly write the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
Advertisements

I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Genome Sciences 373 Genome Informatics Quiz Section 2 April 7, 2015.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Python Control of Flow.
4. Python - Basic Operators
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
If statements while loop for loop
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
More While Loop Examples CS303E: Elements of Computers and Programming.
Built-in Data Structures in Python An Introduction.
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
The If Statement There are no switch statements in Python. You need to use just if statements. There are no switch statements in Python. You need to use.
Control flow Ruth Anderson UW CSE 160 Spring
The Accumulator Pattern Summing: Add up (“accumulate”), e.g. 1 2 plus 2 2 plus 3 2 plus … plus Variation: Form a product (instead of sum), e.g.
: : : | | | Given the pattern of the odd numbers below, which row has 361?
Lists Michael Ernst CSE 140 University of Washington.
Computer Science 101 For Statement. For-Statement The For-Statement is a loop statement that is especially convenient for loops that are to be executed.
Control flow Ruth Anderson UW CSE 160 Winter
Lists Ruth Anderson University of Washington CSE 160 Winter
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
PROGRAMMING INFORMATION. PROCEDURES IN PYTHON Procedures can make code shorter, simpler, and easier to write. If you wanted, for example, to use a certain.
REPETITION CONTROL STRUCTURE
Sequences and Indexing
Algorithmic complexity: Speed of algorithms
Chapter 5 - Control Structures: Part 2
Data Structures: Lists
Ruth Anderson University of Washington CSE 160 Spring 2015
Basic operators - strings
Chapter 10 Lists.
List comprehensions (and other shortcuts) UW CSE 160 Winter 2017.
Ruth Anderson CSE 140 University of Washington
While Loops in Python.
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
Introduction to Python
Lists in Python.
Ruth Anderson University of Washington CSE 160 Spring 2018
Chapter 10 Lists.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Ruth Anderson University of Washington CSE 160 Winter 2017
List comprehensions (and other shortcuts) UW CSE 160 Spring 2018.
Ruth Anderson UW CSE 140 Winter 2014
I210 review.
Michael Ernst UW CSE 140 Winter 2013
String and Lists Dr. José M. Reyes Álamo.
Ruth Anderson UW CSE 160 Winter 2017
3. Decision Structures Rocky K. C. Chang 19 September 2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Algorithmic complexity: Speed of algorithms
Michael Ernst CSE 140 University of Washington
Loops and Arrays in JavaScript
Python Basics with Jupyter Notebook
Algorithmic complexity: Speed of algorithms
Ruth Anderson CSE 160 University of Washington
15-110: Principles of Computing
COMPUTER PROGRAMMING SKILLS
Ruth Anderson UW CSE 160 Spring 2018
Michael Ernst UW CSE 190p Summer 2012
While Loops in Python.
Control flow: Loops UW CSE 160.
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

List comprehensions (and other shortcuts) UW CSE 160 Winter 2016

Three Ways to Define a List Explicitly write out the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Write a loop to create it: squares = [] for i in range(11): squares.append(i * i) Write a list comprehension: squares = [i * i for i in range(11)] A list comprehension is a concise description of a list A list comprehension is shorthand for a loop

Two ways to convert Centigrade to Fahrenheit ctemps = [17.1, 22.3, 18.4, 19.1] With a loop: ftemps = [] for c in ctemps: f = celsius_to_farenheit(c) ftemps.append(f) With a list comprehension: ftemps = [celsius_to_farenheit(c) for c in ctemps] The comprehension is usually shorter, more readable, and more efficient

Syntax of a comprehension [(x, y) for x in seq1 for y in seq2 if sim(x, y) > threshold] expression for clause (required) assigns value to the variable x zero or more additional for clauses zero or more if clauses something that can be iterated

Semantics of a comprehension [(x, y) for x in seq1 for y in seq2 if sim(x, y) > threshold] result = [] for x in seq1: for y in seq2: if sim(x, y) > threshold: result.append( (x, y) ) … use result …

Types of comprehensions List [ i * 2 for i in range(3) ] Set { i * 2 for i in range(3)} Dictionary { key: value for item in sequence …} { i: i * 2 for i in range(3)}

Cubes of the first 10 natural numbers Goal: Produce: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] With a loop: cubes = [] for x in range(10): cubes.append(x ** 3) With a list comprehension: cubes = [x ** 3 for x in range(10)]

Powers of 2, 20 through 210 Goal: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] [2 ** i for i in range(11)]

Even elements of a list Goal: Given an input list nums, produce a list of the even numbers in nums nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]  [4, 2, 6] [num for num in nums if num % 2 == 0]

Dice Rolls Goal: A list of all possible dice rolls. With a loop: for r1 in range(1, 7): for r2 in range(1, 7): rolls.append( (r1, r2) ) With a list comprehension: rolls = [ (r1, r2) for r1 in range(1, 7) for r2 in range(1, 7)]

All above-average 2-die rolls Goal: Result list should be a list of 2-tuples: [(2, 6), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (5, 3), (5, 4), (5, 5), (5, 6), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)] [(r1, r2) for r1 in [1, 2, 3, 4, 5, 6] for r2 in [1, 2, 3, 4, 5, 6] if r1 + r2 > 7] OR [(r1, r2) for r1 in range(1, 7) for r2 in range(8-r1, 7)]

Sum of above-average 2-die rolls Goal: Result list should be a list of integers: [r1 + r2 for r1 in [1, 2, 3, 4, 5, 6] for r2 in [1, 2, 3, 4, 5, 6] if r1 + r2 > 7]  [8, 8, 9, 8, 9, 10, 8, 9, 10, 11, 8, 9, 10, 11, 12] Remove Duplicates: Use Set Comprehensions { r1 + r2 for r1 in range(1, 7) for r2 in range(1, 7) if r1 + r2 > 7}  set([8, 9, 10, 11, 12])

Making a Matrix Goal: A matrix were each element is the sum of it's row and column. With a loop: matrix = [] for i in range(5): row = [] for j in range(5): row.append(i + j) matrix.append(row) With a list comprehension: matrix = [[i + j for j in range(5)] for i in range(5)]

A word of caution List comprehensions are great, but they can get confusing. Err on the side of readability. nums = [n for n in range(100) if sum([int(j) for j in str(n)]) % 7 == 0] nums = [] for n in range(100): digit_sum = sum([int(j) for j in str(n)]) if digit_sum % 7 == 0: nums.append(n)

A word of caution List comprehensions are great, but they can get confusing. Err on the side of readability. nums = [n for n in range(100) if sum([int(j) for j in str(n)]) % 7 == 0] def sum_digits(n): digit_list = [int(i) for i str(n)] return sum(digit_list) sum_digits(n) % 7 == 0]

More shortcuts!

Enumerate a list the_list = [10 ** i for i in range(10)] Or: for i in range(len(the_list)): print str(i) + ': ' + str(the_list[i]) Or: for index, value in enumerate(the_list): print str(index) + ': ' + str(value) index value Like dict.items()

Enumerate a list With a list comprehension: Goal: add each element’s index itself the_list = range(10) new_list = [] for i, v in enumerate(the_list): new_list.append(i + v) With a list comprehension: new_list = [ i + v for i, v in enumerate(the_list) ]

Ternary Assignment A common pattern in python if x > threshold: flag = "Over" else: flag = "Under" Or

Ternary Assignment A common pattern in python if x > threshold: flag = "Over" else: flag = "Under" flag = "Over" if x > threshold else "Under" Ternary Expression Three elements

Ternary Assignment Only works for single expressions as results. flag = "Over" if x > threshold else "Under" Only works for single expressions as results. Only works for if and else (no elif) Result if true Result if false Condition

Ternary Assignment Goal: A list of 'odd' or 'even' if that index is odd or even. the_list = [] for i in range(16): if i % 2 == 0: the_list.append('even') else: the_list.append('odd') or the_list.append('even' if i % 2 == 0 else 'odd')

Ternary Assignment Goal: A list of 'odd' or 'even' if that index is odd or even. the_list = [] for i in range(16): if i % 2 == 0: the_list.append('even') else: the_list.append('odd') or the_list = ['even' if i % 2 == 0 else 'odd' for i in range(16)]

Get more practice List Comprehensions: [(x, y) for x in seq1 for y in seq2 if sim(x, y) > threshold] Enumerate: for index, value in enumerate(seq): … Ternary If Statement: flag = "Over" if x > threshold else "Under"