what is the difference between append and insert in python lists?

0 votes
when working in a list. if i want to add a value, what is the difference between append and insert?

can you show me an example as well?
Mar 15 in Python by Mohammad
• 3,060 points
1,693 views

1 answer to this question.

+2 votes

There is a simple difference between append and insert in python list,
append method can be use for adding new element in the list only but by using insert we can add as well as can modify already occupied position.
append method takes one argument (which you have to insert in the list) while insert method takes two elements (first will be the position of element and second will the element itself), Below are examples for both methods use:

Use of Append:

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

list.append(6)

print(list) # [1,2,3,4,5,6]

Use of Insert:

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

list.insert(5, 10) # [1,2,3,4,5,10]

list.insert(1, 10) # [1,10,3,4,5]
 

You can insert element at any position, but till will be store just after the last element position. Reason behind this logic is list is store data in ordered format. 


list.insert(100, 50) # [1,2,3,4,5,10]

answered Jun 22 by Harshdeep Khatke
Thanks, @Harshdeep, that was a very clear explanation.

Related Questions In Python

+1 vote
1 answer

What is the difference between range and xrange functions in Python 2.X?

xrange only stores the range params and ...READ MORE

answered Aug 22, 2018 in Python by Priyaj
• 56,920 points
276 views
+1 vote
1 answer

What is the difference between print and return in python?

Return statements end the execution of a ...READ MORE

answered Aug 25 in Python by anonymous
179 views
0 votes
0 answers

What is the difference between isdigit, isnumeric and isdecimal in python?

Can you give examples for each of ...READ MORE

May 31 in Python by Waseem
• 4,470 points
314 views
0 votes
2 answers

What is the difference between python lists and arrays?

Python arrays and lists have the same ...READ MORE

answered Jun 10 in Python by Nisa
• 1,090 points
57 views
0 votes
1 answer

What is the difference between str() and repr() functions in Python?

str() is mostly used to create output ...READ MORE

answered Jul 8 in Python by Arvind
• 2,960 points
96 views
0 votes
1 answer

What is the difference between print and pprint in Python?

As per the documentation,  The pprint module provides a capability ...READ MORE

answered Jul 8 in Python by Arvind
• 2,960 points
248 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 334 views