cps6-110922Handout

cps6-110922Handout - CompSci 6 Fall 2011 5 Creating a list...

Info iconThis preview shows pages 1–2. 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 Announcements • Read for next time Chap. 12 • Reading Quiz on Blackboard – Due before class next time • Assignment 3 out today •L ab 4 – More on making decisions, using parameters CompSci 6 Fall 2011 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 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>] •Ex amp l e :
Background image of page 1

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

View Full DocumentRight Arrow Icon
Examples of List Comprehensions [v for v in nums] [2 for v in nums] [v*2 for v in nums]
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 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: • [<expression with variable> for <variable> in <old list> if <filter with variable> ] • 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

This document was uploaded on 01/17/2012.

Page1 / 2

cps6-110922Handout - CompSci 6 Fall 2011 5 Creating a list...

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

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