
Code
List Comprehensions
You've written this loop many times: make an empty list, loop,
append. Python has a shortcut called a list comprehension:
fuel = [3, 0, 8, 1]
# the long way
doubled = []
for f in fuel:
doubled.append(f * 2)
# the comprehension
doubled = [f * 2 for f in fuel] # [6, 0, 16, 2]
Read it as: "f * 2, for each f in fuel". Add an if at the
end to keep only some items:
lit = [f for f in fuel if f > 0] # [3, 8, 1]
You can unpack in the for part too:
pairs = [("Ada", 3), ("Bo", 5)]
names = [name for name, score in pairs] # ['Ada', 'Bo']
Pip tip: comprehensions are for building a new list. If a comprehension stops fitting comfortably on one or two lines, a normal loop is often clearer.
Assignment
Use a list comprehension in each function:
doubled(nums)returns a new list with every number times 2.lit_names(lanterns)gets a list of(name, fuel)tuples and returns the names, in UPPERCASE, of lanterns whose fuel is above0.
Use a list comprehension in each function:
doubled(nums)returns a new list with every number times 2.lit_names(lanterns)gets a list of(name, fuel)tuples and returns the names, in UPPERCASE, of lanterns whose fuel is above0.
main.py Python sleeping
Press Run to try your code, then Check to test it.