Which is more pythonic?
list.append(1)
or
list += [1]
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.
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).
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 .
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.
list.append(1)
is faster, because it doesn't create a temporary list object.
From the Zen of Python:
Explicit is better than implicit.
So: list.append(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With