I tried to rewrite the first block of code with a list comprehension, but it prints a strange list with two None elements.
pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], }
# summarizing the order:
print("You ordered a " pizza['crust'] "-topping" " with:" )
for topping in pizza['toppings']:
print("\t" topping.title())
Second block with the list comprehension:
pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], }
# summarizing the order:
print("You ordered a " pizza['crust'] "-topping" " with:" )
[print("\t" topping.title()) for topping in pizza['toppings']]
Output of the second block:
You ordered a thick-topping with: Mushrooms Extra Cheese [None, None]
I experimented by assigning the list comprehension to a variable, after which the None list disappeared. But I don't understand why.
CodePudding user response:
The problem is that you are including the print
statement in the for
loop, which is non-serializable as a Python function and thus cannot be displayed. What you really want to do is print the list of toppings, not the list of print statements along with the toppings themselves. Try refactoring your code to look like this instead:
print(["\t" topping.title()) for topping in pizza['toppings']])
This will, however, print a list instead of a series of strings, which differs from your original code. If you want to do that with list comprehension, then you'll have to write two lines of code:
toppings = ["\t" topping.title() for topping in pizza['toppings']]
for topping in toppings: print(topping)
In reality, this is much better accomplished using the first method you described and I wouldn't recommend list comprehension unless you're planning to use the toppings
list later on. Generally, list comprehension is very useful for quickly creating lists, but not for executing series of statements, for which a for
loop does a much better job.
CodePudding user response:
Store the Toppings
in a list variable and then iterate over the list to print the values.
Although honestly in this case I would use the first block of code raised.