Python program to add or remove elements from list; Through this tutorial, i am going to show you how to remove or add items or elements from list in python.
How to add and remove items from a list in Python
You can use append and pop() method to add or remove elements or item from list in python:
- Python List append() Method
- Python List pop() Method
Python List append() Method
This method is used to add/append an object (which will be passed in method as parameter) to the list.
Syntax:
list.append(element)
How to add items from a list in Python
See the following python program to add items or elements using append method; as shown below:
# Declaring a list with integer and string elements list = [10, 20, 30, "Bombay", "Pune"] # printing list print("List elements are: ", list) # adding elements list.append (40) list.append (50) list.append ("Kolkata") # printing list after adding elements print("List elements: ", list)
After executing the program, the output will be:
List elements are: [10, 20, 30, 'Bombay', 'Pune'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50, 'Kolkata']
Python List pop() Method
This method is used to remove/pop an object from the list.
Syntax:
list.pop()
How to remove items from a list in Python
See the following python program to remove items from a list ; as shown below:
# Declaring a list with integer and string elements list = [10, 20, 30, "Bombay", "Pune"] # printing list print("List elements are: ", list) # adding elements list.append (40) list.append (50) list.append ("Kolkata") # printing list after adding elements print("List elements: ", list) # removing elements list.pop(); # printing list print("List elements: ", list)
After executing the program, the output will be:
List elements are: [10, 20, 30, 'Bombay', 'Pune'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50, 'Kolkata'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50]
Recommended Python Tutorials
Recommended:-Python Code to Draw a Pie Chart
Recommended:-Python Program to Display the Current Date and Time
Recommended:-Python Program to Find Area of Triangle
Recommended:-Python Program to Find the Area of Rectangle
Recommended:-Python Program to Print All Timezones
Recommended:-Python Count the Occurrences in an Array
Recommended:-Python Program to Print Binary Numbers From 1 to N
Recommended:-Python Program to print Elements in a List
Recommended:-Python Program to Swap Characters of Given String
Recommended:-Swap First Two Characters in Each String in Python
Recommended:-Python Split String into Array of Characters
Recommended:-Python Program to Reverse String Using Stack
Recommended:-Python Insert Element at Specified Index in List