Understanding Python 3 lists printing None value for each element

前端 未结 2 1143
小蘑菇
小蘑菇 2020-11-30 14:58

As a very noob with in Python I\'m printing all elements of a list in version 3, and after a comprehensive research I couldn\'t find an explanation for this kind of behavior

相关标签:
2条回答
  • 2020-11-30 15:34

    As mentioned by others, print() does not return anything. Hence, None is printed. If you are wondering why the elements are properly printed, and then followed by 2 None's, its because of how functions work.

    A function is called and once every statement inside has been executed, a value is returned, but only if the function returns something.

    In your case, print(f) was the call to the print function on f, print was executed, meaning that it printed the required value to the console, and then its value was returned, which is None, since print() does n't return anything. As you are working in the shell, each expression is printed directly, and thus, you get both the expected elements along with the None's.

    Coming to the solution, you could use a simple loop as mentioned in other answers

    The output:

    1
    2
    
    0 讨论(0)
  • 2020-11-30 15:56

    None is the return value of the print function.

    Don't use [print(f) for f in a_list] when you mean for f in a_list: print(f).

    0 讨论(0)
提交回复
热议问题