[Tutor] append vs list addition

Steven D'Aprano steve at pearwood.info
Sun May 4 16:29:14 CEST 2014


On Sun, May 04, 2014 at 09:51:17AM -0400, C Smith wrote:
> Sorry.
> 
> I meant for example:
> list1 = [1,2,3]
> list2 = [3,4,5]
> 
> newList = list1 + list2

This creates a new list, containing the same items as list1 and list2.

> versus
> 
> for x in list2:
>     list1.append(x)

This can be written more simply as list1.extend(list2). Either way, it 
doesn't create a new list, it modifies list1 in place.


> Which is the preferred way to add elements from one list to another?

Depends on what you want to do. The two code snippets do very different 
things. In the first case, you end up with three lists:

list1 = [1, 2, 3]  # unchanged
list2 = [3, 4, 5]  # unchanged
newlist = [1, 2, 3, 3, 4, 5]

If that's what you want, then using list addition is exactly the right 
solution. In the second case, you end up with two lists:

list1 = [1, 2, 3, 3, 4, 5]  # changed in place
list2 = [3, 4, 5]  # unchanged

If that's the result you want, then using the extend method (or append, 
repeatedly) is exactly the right solution. Keep in mind that because 
list1 is changed in place, any other references to it will see the same 
change:

py> data = {'key': list1, 'another': list2}
py> list1.extend(list2)
py> print data
{'another': [3, 4, 5], 'key': [1, 2, 3, 3, 4, 5]}


The second example (using extend) is possibly a little faster and more 
efficient, since it doesn't have to copy list1. But sometimes you *need* 
a copy, in which case, use addition.



-- 
Steven


More information about the Tutor mailing list