LoginSignup
8
5

More than 5 years have passed since last update.

内包表記の中でprintしたい

Last updated at Posted at 2015-10-16

内包表記の確認

for文内を確認したい時に、内包表記で書いてると少しめんどくさい。
そもそも、内包表記の中ではprintは書けない。

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

こんな感じでエラーが出てしまいます。
printはそもそも関数ではないため、内包表記ないでは書けません。
なので、

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]

こんな感じに関数を作ってあげれば、printも出来るしリストの生成もできるようになります。

python3

python3ではprintは関数となっている。

python2系から3系では幾つかの変更があります。
その一つが、printが関数となっていることです。

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]

上記を見てみると、printは関数なので()で囲ってあげないとエラーが出ます。
また、内包表記の中で書いてもエラーが出なくなります。

参考

下記のURLにて、2と3の違いが分かりやすくまとめて載っていますので興味がある方はどうぞ。
http://postd.cc/the-key-differences-between-python-2-7-x-and-python-3-x-with-examples/

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5