Python append vs extend

Append adds an element to the end of a list. Extend adds elements from another list (or any iterable) to the end of the list. So if you have a list, l, and you want to add 3 more elements to it, you can do either:

l.append(1)

l.append(2)

l.append(3)

or:

l.extend([1, 2, 3])

The difference is that the latter will keep l as a flat list, while the former will make it a nested list. So if you have a list, l, and you want to add 3 more elements to it, you can do either:

l.append(1)

l.append(2)

l.append(3)

or:

l.extend([1, 2, 3])

The difference is that the latter will keep l as a flat list, while the former will make it a nested list. If you’re just adding one element, it doesn’t matter which you use. But if you’re adding multiple elements (especially from another list), extend is usually what you want.

When would you use one over the other?

If you want to add a single element to the end of a list, you would use append. If you want to concatenate two lists, you would use extend.

How do they differ in terms of performance

In terms of performance, append is faster than extend. This is because extend requires allocating a new list and copying over the elements from the old list, while append only requires adding a new element to the end of the list.

Examples of when to use append and when to use extend

When you’re just adding a single element to the end of a list, use append. For example:

l = [‘a’, ‘b’, ‘c’]

l.append(‘d’)

print(l)

This will print [‘a’, ‘b’, ‘c’, ‘d’].

When you’re concatenating two lists, use extend. For example:

l1 = [‘a’, ‘b’, ‘c’]

l2 = [‘d’, ‘e’, ‘f’]

l1.extend(l2)

print(l1)

This will print [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]. Note that l1 is now a flat list. If you had used append instead, l1 would be a nested list:

l1 = [‘a’, ‘b’, ‘c’]

l2 = [‘d’, ‘e’, ‘f’]

l1.append(l2)

print(l1)

This will print [‘a’, ‘b’, ‘c’, [‘d’, ‘e’, ‘f’]].

In terms of performance, append is faster than extend. This is because extend requires allocating a new list and copying over the elements from the old list, while append only requires adding a new element to the end of the list.

Which is better for your specific needs

Will depend on what you’re trying to do. If you’re just adding a single element to the end of a list, append is probably what you want. If you’re concatenating two lists, extend is probably what you want. In terms of performance, append is faster than extend.

Both append and extend are useful methods for adding elements to a list. The main difference is that append adds an element to the end of a list, while extend adds elements from another list (or any iterable) to the end of the list. In terms of performance, append is faster than extend. Which you use will depend on your specific needs.