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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.