Python Forum

Full Version: dilemma with list comprehension
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
the output of list comprehension is always list That was my perception.
Now I encountered something like below and I am confused. It is not yielding a list

number = int(input("Enter a number: "))

[print(f"{number} x {number_2} = {number * number_2}") for number_2 in range(1, 21)]
this is ugly abuse of list comprehension. The only reason to use list comprehension is to exploit side-effect and turn 2-line loop into one-liner
number = int(input("Enter a number: "))
for number_2 in range(1, 21):
    print(f"{number} x {number_2} = {number * number_2}")
zen of python
(Aug-14-2020, 09:07 AM)spalisetty06 Wrote: [ -> ]It is not yielding a list
it's yielding a list, but it's thrown-away, because it's not assigned to a variable. Because print() function will return None, it will be list of 20 None values.
number = int(input("Enter a number: "))
foo = [print(f"{number} x {number_2} = {number * number_2}") for number_2 in range(1, 21)]
print(foo)