[Tutor] append vs list addition

Dave Angel davea at davea.name
Mon May 5 03:44:03 CEST 2014


C Smith <illusiontechniques at gmail.com> Wrote in message:
> Sorry.
> 
> 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?

Thank you for switching to text mail.

These examples still aren't equivalent.  But in any similar
 example,  if list2 is type list, then avoid the list. Use either
 extend, or the equivalent += . And if you aren't permitted to
 change list1, you should use += .

The time when append is preferred over + is when you HAVE to loop
 over the items,  like when they each need computing or when
 they're output from a generator. 



-- 
DaveA



More information about the Tutor mailing list