Home » Python

append() and extend() in Python

Python List append() and extend() methods: In this tutorial, we are going to learn about the List append() and extend() methods in Python programming language with examples.
Submitted by IncludeHelp, on March 05, 2020

List append() method

append() method is used to insert an element or a list object to the list and length of the List increased by the 1.

Syntax:

    List.append(element/object)

Example 1:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before appending
print("list1: ", list1)
print("len(list1): ", len(list1))

# appending an element to the list
list1.append(60)

# printing the list after  appending
print("list1: ", list1)
print("len(list1) ", len(list1))

Output

list1:  [10, 20, 30, 40, 50]
len(list1):  5
list1:  [10, 20, 30, 40, 50, 60]
len(list1)  6

Example 2:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before appending
print("list1: ", list1)
print("len(list1) ", len(list1))

# appending a list object to the list
list2 = [60, 70, 80]
list1.append(list2)

# printing the list after  appending
print("list1: ", list1)
print("len(list1) ", len(list1))

Output

list1:  [10, 20, 30, 40, 50]
len(list1)  5
list1:  [10, 20, 30, 40, 50, [60, 70, 80]]
len(list1)  6

List extend() method

extend() method is used to extend the list by inserting the given number of elements or given list and the length of the List increased by the total number of elements added.

Syntax:

    List.extend(another_list)

Note: If we append a list, then the list appended as an element to the List, thus, the length of the list increased by 1. While, if we extend a list by a list, then the list extended by the given number of elements in the list (which is passed as an argument), thus, the length of the list increased by the given number of elements in the list which is going to be added.

Example:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before extending
print("list1: ", list1)
print("len(list1) ", len(list1))

# extending the list with another list
list2 = [60, 70, 80]
list1.extend(list2)

# printing the list after  extending
print("list1: ", list1)
print("len(list1) ", len(list1))






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.