Examples of adding and inserting elements in Python

  • 2021-01-18 06:35:08
  • OfStack

In Python, append is used to append a single element to the end of list. If the added element is a single list, then the list is appended as a whole.

Such as:

Python code


li=['a', 'b'] 
li.append([2,'d']) 
li.append('e') 
# The output is: ['a', 'b', [2, 'd'], 'e'] 

In Python, insert is used to insert individual elements into list. The numeric parameter is the index of the insertion point.

Such as:


#Python code 
li=['a', 'b'] 
li.insert(0,"c") 
# The output is :['c', 'a', 'b'] 

extend is used to connect list to Python.

Such as:

Python code


li=['a','b'] 
li.extend([2,'e']) 
# The output is: ['a', 'b', 2, 'e'] 

Related articles: