Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write each loop as a list comprehension.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. The shape is [expression for item in iterable if condition]. The expression is what is appended, and the condition is the if.
len(w) for every word: [len(w) for w in words].w.upper() only when len(w) > 3: [w.upper() for w in words if len(w) > 3].Check. The lengths are 3, 8, 3 and 5. The words longer than 3 letters are notebook and ruler, in capitals.
Answer: [3, 8, 3, 5] and ['NOTEBOOK', 'RULER'].
Log in to join the discussion.
Loading…