Python

Python: what is the difference between append and extend in a list?

March 22, 2022

Python: what is the difference between append and extend in a list?

In this article, you will learn the difference between append and extend in a list, methods that are often used when working with lists in Python.

difference between append and extend in a list thumb

Hey you programmer, how are you? Let’s learn more about Python!

When working with lists in Python we have two methods that look very similar: append and extend

But they have some subtle differences, append takes an iterable as a parameter

We can describe iterable as a data type that has several elements that can be iterated, a list for example

This  iterable argument expands the list, adding the elements to the end, let’s see an example:

listA = [1,2,3,4,5]
listB = [6,7,8]

listA.extend(listB)

print(listA)

This way each of the elements of listB will be added to the end of listA, let’s see the result:

[1, 2, 3, 4, 5, 6, 7, 8]

In turn, append will simply add the entire element to the end of the list.

Regardless of the data type or if it is an iterable, check it out:

listC = [1,2,3,4,5]

wordA = 'test'

listC.append(wordA)

print(listC)

listD = [99,100]

listC.append(listD)

print(listC)

See that even adding another iterable, Python simply added it into the list as if it were another element, as shown in the result:

[1, 2, 3, 4, 5, 'test']
[1, 2, 3, 4, 5, 'test', [99, 100]]

So, regardless of the data type, append will place the element in its final list and in the last position

Now it’s easier to choose one of them, right? 😀

Conclusion

In this article we learnde the difference between append and extend in a list

Basically append will add any element to the end of your list

The extend already takes an iterable as an argument, and adds each of these elements of the iterable to the end of the list

Do you wanna learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x