1

I'm testing some Django functionality in my interactive shell

Here's my attempt to probe these objects, note the list of Nones at the end

>>> [print(foo) for foo in CharacterSkillLink.objects.all() if foo.speciality]
Streetwise (Street Countdown) Roran
[None]

And with a more orthodox list comprehension:

>>> [print(foo) for foo in range(1,10)]
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None]

Nine Nones, all in a row.

Why am I getting that?

Igor Hatarist
  • 5,234
  • 2
  • 32
  • 45
AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173

2 Answers2

6

Because print returns a value, namely None. What it prints and what it returns are two different things.

André Laszlo
  • 15,169
  • 3
  • 63
  • 81
1

This is because, you use Python 3.x, in which print function returns None after printing to the console and thus you are getting this output. Whereas, if you have used Python 2.x, you will correctly get a SyntaxError for the print function.

A better example will be this(in python 2.x as your example wont work in python 2.x)

>>> b = []
>>> [b.append(i) for i in range(10)]
...[None, None, None, None, None, None, None, None, None, None]
>>> print b
...[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you wish to print things AND add it to the list, it should be like this:

[(print(foo) or foo) for foo in CharacterSkillLink.objects.all() if foo.speciality]

However, in my view, refrain from using such things as things might get ugly after some period of time.

thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26