Name: ______________ Net id: _____________ || Name: ______________ Net id: _____________ Name: ______________ Net id: _____________ || Name: ______________ Net id: _____________
Python has a language feature called a list comprehension that allows you to create a list from another list/sequence. For example the list comprehensions below generate the output shown.
Traditional for loop | List Comprehension | Resulting list |
---|---|---|
result = range(0, 10) for i,x in enumerate(result): result[i] = x*2 |
[x*2 for x in range(0,10)] |
[0,2,4,6,8,10,12,14,16,18] |
words = ['apple','termite','elephant'] result = [] for s in words: result.append(s[0]) |
[s[0] for s in ['apple','termite','elephant']] |
['a','t','e'] |
numbers = [2,4,6,1,3,5,8] result = [] for n in numbers: if n % 2 == 0: result.append(n) |
[n for n in [2,4,6,1,3,5,8] if n % 2 == 0] |
[2,4,6,8] |
numbers = [2,4,6,1,3,5,8] result = numbers[:] # copy list for i,n in enumerate(result): result[i] = (n % 2 == 0) |
[n % 2 == 0 for n in [2,4,6,1,3,5,8]] |
[True,True,True,False,False,False,True] |
Without typing on any computer, (so by thinking) show the resulting list for each line below.
[x**2 for x in range(1,10,2)] [s[1] for s in ["apple", "big", "brown", "bare", "stem", "pea"]] ['po'*i for i in range(0,5)] [i*i for i in range(1,10) if i % 2 == 0] [x for x in "ostentatiously" if "aeiou".find(x) > -1]
rc
:
counts
:
win (7 or 11) = lose (2, 3, or 12) =
What odds did you calculate for each of the following poker hands?