Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Python
A = [4, 6, 1]
A.append(8)
A.extend([9, 11])
A += [3, 5]
print(A)

What I have tried:

Nothing...............................................................................................
Posted
Updated 4-Aug-17 6:44am

1 solution

There is no "better", because they have different purposes:

.append adds a single element to the list.

.extend is like append but for multiple elements: it takes a list as argument.

a += [3, 5] is short-hand for a = a + [3, 5] and this does the same as extend, but the difference is that the + operator won't overwrite the original list (unless you do it manually using =), whereas .extend will always modify the original list. So if you wanted another list rather than overwriting a, you'd do b = a + [3, 5], and you can't do this with extend.
 
Share this answer
 
v2
Comments
Zarif Muhtasim 4-Aug-17 12:47pm    
So....do you prefer using += ?
Thomas Daniels 4-Aug-17 12:51pm    
For a single element, I definitely use .append.

For multiple elements, where I'd have to choose between extend and +=, I'd go with extend, but it doesn't really matter.
Zarif Muhtasim 4-Aug-17 12:57pm    
Why should you use append() for a single element or item
Thomas Daniels 4-Aug-17 13:00pm    
Because that's what it is made for. Using extend or += for a single element for sure won't have any benefit.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900