Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list + list vs. list.append()

Tags:

python

list

Today I spent about 20 minutes trying to figure out why this worked as expected:

users_stories_dict[a] = s + [b] 

but this would have a None value:

users_stories_dict[a] = s.append(b)

Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was made; it looks like a Python novice gotcha to me right now.

like image 395
worker1138 Avatar asked Apr 08 '11 01:04

worker1138


People also ask

What is the difference between append () and extend () methods of list?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

Is += list the same as append?

In general case append will add one item to the list, while += will copy all elements of right-hand-side list into the left-hand-side list.

How append () and extend () are different with reference to list in Python?

Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.

Does append work for lists?

append() that you can use to add items to the end of a given list. This method is widely used either to add a single item to the end of a list or to populate a list using a for loop. Learning how to use . append() will help you process lists in your programs.


1 Answers

append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is:

s.append(b)

and then:

users_stories_dict[a] = s

But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0 (or false) exit value indicating that an operation proceeded normally, and by returning None for functions whose role is to modify their arguments in-place you report that the modification succeeded.

But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.

like image 165
Approximately Linear Avatar answered Sep 17 '22 17:09

Approximately Linear