Difference between Python's list methods append() and extend()

Python | append() vs. extend() Methods: Here, we are going to learn about the difference between Python's list methods append() and extend() with examples.
Submitted by IncludeHelp, on June 25, 2020

Both methods append() and extend() are used to insert elements in a list.

append():

append() method appends the object at the end i.e. it appends argument as a single element at the end of the list.

Syntax:

list.append(object)

Example:

list1 = [10, 20, 30]
list2 = [40, 50, 60]

# printing the list before 
# append() operation
print("list1:", list1)
print("list2:", list2)

# appending the list2 in list1
list1.append(list2)

# printing the list
print("After append, list1:", list1)

Output:

list1: [10, 20, 30]
list2: [40, 50, 60]
After append, list1: [10, 20, 30, [40, 50, 60]]

See the output, list2 is added as an object in the list1.

extend():

extend() method extends the list by appending the elements of the given object/iterable i.e. it appends argument as elements at the end of the list.

Syntax:

list.extend(object)

Example:

list1 = [10, 20, 30]
list2 = [40, 50, 60]

# printing the list before 
# extend() operation
print("list1:", list1)
print("list2:", list2)

# appending the list2 in list1
list1.extend(list2)

# printing the list
print("After extend, list1:", list1)

Output:

list1: [10, 20, 30]
list2: [40, 50, 60]
After extend, list1: [10, 20, 30, 40, 50, 60]

See the output, list2 is added as elements in the list1.

Conclusion:

Thus, the basic difference is between append() and extend() method is that append() appends the argument as an object while extend() appends the argument as elements.

Read more: append() and extend() in Python



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.