{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

cps6-110922Handout

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

This preview shows pages 1–2. Sign up to view the full content.

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 Lab 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>] • Example: nums = [8, 3, 5, 4, 1] sqnums = [v*v for v in nums] CompSci 6 Fall 2011 4

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

View Full Document
Examples of List Comprehensions [v for v in nums] [2 for v in nums] [v*2 for v in nums]
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

{[ snackBarMessage ]}