question about list extension

Lie Ryan lie.1296 at gmail.com
Fri Apr 16 10:37:50 EDT 2010


On 04/16/10 23:41, J wrote:
> Ok... I know pretty much how .extend works on a list... basically it
> just tacks the second list to the first list... like so:
> 
>>>> lista=[1]
>>>> listb=[2,3]
>>>> lista.extend(listb)
>>>> print lista;
> [1, 2, 3]
> 
> what I'm confused on is why this returns None:
> 
>>>> lista=[1]
>>>> listb=[2,3]
>>>> print lista.extend(listb)
> None
>>>> print lista
> [1, 2, 3]
> 
> So why the None? Is this because what's really happening is that
> extend() and append() are directly manipulating the lista object and
> thus not actuall returning a new object?

In python every function that does not explicitly returns a value or use
a bare return returns None. So:

def foo():
    pass
def bar():
    return

print foo()
print bar()

you can say that returning None is python's equivalent to void return
type in other languages.

> Even if that assumption of mine is correct, I would have expected
> something like this to work:
> 
>>>> lista=[1]
>>>> listb=[2,3]
>>>> print (lista.extend(listb))
> None

Why would these has to be different?
print None
print (None)

<snip>

> So, what I'm curious about, is there a list comprehension or other
> means to reduce that to a single line?

from itertools import chain
def printout(*info):
    print '\n'.join(map(str, chain(*info)))

or using generator comprehension

from itertools import chain
def printout(*info):
    print '\n'.join(str(x) for x in chain(*info))



More information about the Python-list mailing list