Printing using list comprehension

后端 未结 10 1692
一生所求
一生所求 2020-12-03 10:58

From my Python console

>>> numbers = [1,2,3]
>>> [print(x) for x in numbers]
1
2
3
[None, None, None]

Why does this print

相关标签:
10条回答
  • 2020-12-03 11:53

    3 ways to print using list comps:

    1. print outside

    print([(i) or i for i in range(4)])

    1. create a function

    def printVal(val): print("val: ", val) return val

    [printVal(i) or i for i in range(4)]

    1. Use 'or'

    [print(i) or i for i in range(4)]

    0 讨论(0)
  • 2020-12-03 11:56

    The print function returns None. The list comprehension is applying the function to each element of the list (outputting the results), but collecting those None objects into the results array. The Python interpreter is printing that array.

    0 讨论(0)
  • 2020-12-03 11:57

    print is a function in Python 3, which returns a None. Since you are calling it three times, it constructs a list of three None elements.

    0 讨论(0)
  • 2020-12-03 12:03

    You should restructure your loop to send arguments to print():

    >>> numbers = [1,2,3]
    >>> print(*(x for x in numbers), sep='\n')
    

    Note that you don't need the explicit generator. Just unpack the list itself:

    >>> numbers = [1,2,3]
    >>> print(*numbers, sep='\n')
    
    0 讨论(0)
提交回复
热议问题