Difference between Python’s list methods append and extend

Difference between Python’s list methods append and extend ?

This tutorial guides you on the difference between Python’s list methods append() and extend() methods.

Difference between Python’s list methods append and extend

Difference between Python’s list methods append and extend

Both the methods are defined for Mutable Sequence Types. Here is the list of operations defined on mutable sequence types. Let’s try to learn the exact difference between these two operations with examples below.

list.append() example

It appends the sequence seq2 to the end of the sequence seq1. Therefore, it results in a nested list and it does not look like a flatten list.

Syntax:

seq1.append(seq2)

For example,

>>> x = [10,20,30]

>>> x.append([11,22])

>>> x
[10, 20, 30, [11, 22]]

list.extend() example

It extends the sequence seq1 with the contents of sequence seq2. Therefore, the resulted list looks like a flatten list.

Syntax:

seq1.extend(seq2)

We can say that the above syntax is equivalent to:

seq1 += seq2

For example,

>>> y = [10,20,30]

>>> y.extend([11,22])

>>> y
[10, 20, 30, 11, 22]

Difference between list’s append() and extend() methods

From the above examples, it is understood that append() adds the list object to the end of the list. Therefore, the length of the list increase by 1.

And in case of extend(), it iterates the list elements passed as an argument and add each element to the list. Therefore it results in extending the list and the length of the list increase by the number of elements that were iterated/ iterable in the argument.

That’s it. You had learnt the difference between list’s append and extend methods with examples.

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments