list comprehension question

Chris Rebert clp2 at rebertia.com
Wed Feb 29 18:10:31 CET 2012


On Wed, Feb 29, 2012 at 5:52 AM, Johann Spies <johann.spies at gmail.com> wrote:
> I understand the following:
>
> In [79]: instansie
> instansie
> Out[79]: 'Mangosuthu Technikon'
>
> In [80]: t = [x.alt_name for x in lys]
> t = [x.alt_name for x in lys]
>
> In [81]: t
> t
> Out[81]: []
>
> In [82]: t.append(instansie)
> t.append(instansie)

Note the lack of an accompanying "Out". This means that the
expression, i.e. `t.append(instansie)`, had a result of None.
The list.append() method does *not* return the now-appended-to list.
It is a mutator method that modifies the list object in-place; per
convention, it therefore returns None to reinforce its side-effecting
nature to the user; analogous methods in other languages return void.

> In [83]: t
> t
> Out[83]: ['Mangosuthu Technikon']
>
> But then why does the following behave like this:
>
> In [84]: t = [x.alt_name for x in lys].append(instansie)
> t = [x.alt_name for x in lys].append(instansie)

You didn't do anything with .append()'s useless return value before;
here, you do, by assigning it to t.

> In [85]: t
> t
>
> In [86]: type t
> type t
> -------> type(t)
> Out[86]: NoneType

Cheers,
Chris



More information about the Python-list mailing list