NoneType List
Alan Gauld
learn2program at gmail.com
Sat Dec 31 04:09:04 EST 2022
On 31/12/2022 05:45, Goran Ikac wrote:
> b = a.append(3)
> I mean: why b = a.append(something) is the None type, and how to make a new
> list that contains all the items from a and some new items?
append() like many other collection methods in Python works
in place and returns None. But the action has succeeded
and 3 will have been appended to list 'a'.
So, to create a new list that contains all the old items you could do:
newlist = [] # an empty list
for item in oldlist:
newlist.append(item)
This is so common Python has a shorthand form to do this:
newlist = [item for item in oldlist]
called a list comprehension.
And there is an even shorter way using something called slicing:
newlist = oldlist[:] # copy oldlist to new.
However, as an ex-Smalltalk programmer, I do wish that Python
returned self from these methods rather than None so that
we could chain them. But sadly it doesn't.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Python-list
mailing list