Home » Python » Python programs

List append() and insert() methods in Python

Python list append() and insert() methods: Here, we are going to learn about the append() and insert() methods with example.
Submitted by Sanjeev, on April 06, 2019

Python list supports variety of built-ins functions in which append() and insert() are two functions

1) Python append() method

append() method is used to append values at the last position of the list that is every time you append a value it will directly go to the last of the list.

append() method takes only one argument.

Syntax:

    list_name.append( any value )

Python insert() method

insert() method is also used to insert values in a list but the advantage of insert() method over append() method is that with the help of insert() method one can insert the values at any particular index (index should be less than the size of the list).

insert() method takes 2 argument one is index and other is value.

Syntax:

    list_name.insert( index_value, any value )

Python code to demonstrate use, differences of append() and insert() methods

lst = [1, 2, 3, 4, 5, 6]

print('Original list:',*lst)

# appending two values in the
# existing list to show the
# working of append() function
lst.append(9)
lst.append(15)

print('\nList after appending 9 and 15')
print(*lst)

# inserting value 20 at index 2
lst.insert(2,20)

# inserting string literal 'include'
# at index 6
lst.insert(6,'include')

print('\nList after inserting 20 and "include"')
print(*lst)
print()

Output

Original list: 1 2 3 4 5 6

List after appending 9 and 15
1 2 3 4 5 6 9 15

List after inserting 20 and "include"
1 2 20 3 4 5 include 6 9 15





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.