CSC148H1 Lecture Notes - Lecture 3: List Comprehension, For Loop, Duck Typing

43 views11 pages
13 Nov 2017
School
Course
Professor
katrinasavvy and 38715 others unlocked
CSC148H1 Full Course Notes
1
CSC148H1 Full Course Notes
Verified Note
1 document

Document Summary

List comprehensions (listcomps for short) are syntax shortcuts for this general pattern: The traditional way, with for and if statements: new_list = [] for item in a_list: if condition(item): new_list. append(fn(item)) As a list comprehension: new_list = [fn(item) for item in a_list if condition(item)] Listcomps are clear & concise, up to a point. You can have multiple for-loops and if-conditions in a listcomp, but beyond two or three total, or if the conditions are complex, i suggest that regular for loops should be used. Applying the zen of python, choose the more readable way. For example, a list of the squares of 0 9: >>> [n ** 2 for n in range(10)] A list of the squares of odd 0 9: >>> [n ** 2 for n in range(10) if n % 2] Let"s sum the squares of the numbers up to 100: As a loop: total = 0 for num in range(1, 101): total += num * num.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents