[Tutor] append vs list addition
Peter Otten
__peter__ at web.de
Sun May 4 16:29:27 CEST 2014
C Smith wrote:
> I meant for example:
> list1 = [1,2,3]
> list2 = [3,4,5]
>
> newList = list1 + list2
>
> versus
>
> for x in list2:
> list1.append(x)
>
> Which is the preferred way to add elements from one list to another?
None of the above unless you need to keep the original list1. Use
list1.extend(list2) # 1
or
list1 += list2 # 2
I prefer (1), but both do the same under the hood: append all items from
list2 or any iterable to list1.
If you want to preserve the original list1
new_list = list1 + list2
is fine.
More information about the Tutor
mailing list