The difference between append and extend in Python

Asked 2 years ago, Updated 2 years ago, 147 views

What is the difference between append() and extend() in the Python list method?

list python append

2022-09-21 18:49

1 Answers

append() adds the object at the end.

x = [1, 2, 3]
x.append([4, 5])
print (x)

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

extend() appends the elements of an optional object (list, tuple, dictionary, etc.) to the list.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

[1, 2, 3, 4, 5]


2022-09-21 18:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.