When you want to check the inside of the for sentence, it is a little annoying to write it in the inclusion notation. In the first place, print cannot be written in the comprehension.
terminal.
$ python
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num_list = [1,2,3,4,5]
>>> [print(i) for i in num_list]
File "<stdin>", line 1
[print(i) for i in num_list]
^
SyntaxError: invalid syntax
I get an error like this. Since print is not a function in the first place, it cannot be written without comprehension. So
terminal.
>>> def puts(i):
... print i
... return i
...
>>> [puts(i) for i in num_list]
1
2
3
4
5
[1, 2, 3, 4, 5]
If you create a function like this, you will be able to print and generate a list.
python3
There are some changes in python2 to 3 series. One of them is that print is a function.
python3.
$ python3
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World!")
Hello World!
>>> print "Hello World!"
File "<stdin>", line 1
print "Hello World!"
^
SyntaxError: Missing parentheses in call to 'print'
>>> num_list = [1,2,3,4,5]
>>> [print(i) for i in num_list]
1
2
3
4
5
[None, None, None, None, None]
Looking at the above, print is a function, so if you do not enclose it in (), you will get an error. Also, even if you write in the comprehension notation, no error will occur.
If you are interested, please see the URL below for the differences between 2 and 3 in an easy-to-understand manner. http://postd.cc/the-key-differences-between-python-2-7-x-and-python-3-x-with-examples/
Recommended Posts