Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python 3 lists printing None value for each element

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.

However, I know every function must return some value and when it's not defined the function returns "Null" (or "None" in Python). But why in this case, after printing all elements correctly it prints "None" for each element in another list?

>>> a_list = [1,2]
>>> a_list
[1, 2]
>>> [print(f) for f in a_list]
1
2
[None, None]
like image 313
adamitj Avatar asked Oct 03 '22 12:10

adamitj


2 Answers

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).

like image 189
Dan D. Avatar answered Oct 07 '22 19:10

Dan D.


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
like image 44
Polaris000 Avatar answered Oct 07 '22 18:10

Polaris000