







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
List comprehensions provide a more compact and ... expr is Python expression, typically involving the variable x. ... Nested List Comprehensions. Example:.
Typology: Study notes
1 / 13
This page cannot be seen from the preview
Don't miss anything!








M A R C H 2 4 T H^ , 2 0 1 4
[x**2 for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [str(x)+str(x) for x in range(10)] ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99'] [str(x)+str(x) for x in range(10) if x%2 == 0] ['00', '22', '44', '66', '88']
[ expr for x in list] Notes: for and in are Python keywords, used just as in for-loops. x is a variable that takes on values of elements in list, in order. expr is Python expression, typically involving the variable x. The expression [ expr for x in list] evaluates to a list made up of the different values that expr takes on for different x. This is similar to the “set builder” notation used in math: {x*y | x and y are even}.
evaluates to ['00', '22', '44', '66', '88']
Example: [x*y for x in range(3) for y in range(3)] [0, 0, 0, 0, 1, 2, 0, 2, 4] Notes:
2
primes = [x for x in range(2, 100) if x not in composites] Notes: Primes in the range 2..99 can be obtained by taking the complement of the generated composites.
nestedList = [range(x) for x in range(1, 4)] nestedList [[0], [0, 1], [0, 1, 2]] [y for x in nestedList for y in x] [0, 0, 1, 0, 1, 2]