Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.append or list +=?

Tags:

python

Which is more pythonic?

list.append(1) 

or

list += [1] 
like image 405
Dick Sea Mongler Avatar asked May 09 '09 17:05

Dick Sea Mongler


People also ask

Is += list the same as append?

For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.

Can we append a list to a list?

append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).

What does append do to a list?

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 .

What is the use of append () in list give example?

The Python List append() method is used for appending and adding elements to the end of the List. Parameters: item: an item to be added at the end of the list.


2 Answers

list.append(1) is faster, because it doesn't create a temporary list object.

like image 74
pts Avatar answered Sep 21 '22 13:09

pts


From the Zen of Python:

Explicit is better than implicit.

So: list.append(1)

like image 40
joce Avatar answered Sep 25 '22 13:09

joce