Exercise
Q1: | Create a composite list comprehension statement that creates (randomly) a list of between 1 and 10 random numbers, ranging from 1 to 100, and pull out only the odd ones. |
A1: | Answer:
Our solution uses list comprehensions as well as the new extended import syntax. >>> from random import randint as ri >>> [ y for y in [ ri(1, 100) for x in range(ri(1, 10)) ] if y % 2] [47, 9, 85] >>> [ y for y in [ ri(1, 100) for x in range(ri(1, 10)) ] if y % 2] [45, 3] >>> [ y for y in [ ri(1, 100) for x in range(ri(1, 10)) ] if y % 2] [] >>> [ y for y in [ ri(1, 100) for x in range(ri(1, 10)) ] if y % 2] [47, 25, 95, 83, 15, 77] |
Get Core Python Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.