cps6-110922

cps6-110922 - [2 for v in nums] [v*2 for v in nums] CompSci...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
CompSci 6 Introduction to Computer Science September 22, 2011 Prof. Rodger CompSci 6 Fall 2011 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Announcements • Read for next time Chap. 12 • Reading Quiz on Blackboard – Due before class next time • Assignment 3 out today • Lab 4 – More on making decisions, using parameters CompSci 6 Fall 2011 2
Background image of page 2
Creating a list • Given a list of numbers, create a second list of every number squared. nums = [8, 3, 5, 4, 1] sqnums = [] for v in nums: sqnums.append(v*v) print sqnums [64, 9, 25, 16, 1] CompSci 6 Fall 2011 3
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
List Comprehension • Take advantage of patterns, make a new list based on per element calculations of another list • Format: [<expression with variable> for <variable> in <old list>] • Example: nums = [8, 3, 5, 4, 1] sqnums = [v*v for v in nums] CompSci 6 Fall 2011 4
Background image of page 4
Examples of List Comprehensions [v for v in nums]
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: [2 for v in nums] [v*2 for v in nums] CompSci 6 Fall 2011 5 Creating a list with just the even numbers nums = [8, 3, 5, 4, 1] evennums = for v in nums: if v % 2 == 0: evennums.append(v) print evennums [8, 4] CompSci 6 Fall 2011 6 List Comprehension with Filtering Create list and use if to filter out elements to the list Format: [&lt;expression with variable&gt; for &lt;variable&gt; in &lt;old list&gt; if &lt;filter with variable&gt; ] Example: nums = [8, 3, 5, 4, 1] evennums = [v for v in nums if v%2==0] CompSci 6 Fall 2011 7 More on List Comprehensions Do examples of list comprehensions Problem: Given a list of strings, return the longest string. If there are more than one of that length, return the first such one. [kiwi, plum,orange, lemon, banana] CompSci 6 Fall 2011 8...
View Full Document

Page1 / 8

cps6-110922 - [2 for v in nums] [v*2 for v in nums] CompSci...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online