Thursday, December 26, 2024
Google search engine
HomeLanguagesPython Add and Remove Elements From List

Python Add and Remove Elements From List

To add and remove items from a list in Python; In this tutorial, you will learn how to add and remove items or elements from a list in python program.

Python has two methods first is append(), which is used to add an element in list. And the second method is pop, which is used to remove an element from list. Also, we will share these two methods by programs.

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)

Python Program to add elements in list

# 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()

Python Program to remove elements from list

# 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 List Programs

  1. How to Input List From User in Python
  2. Python Add and Remove Elements From List
  3. Python Program to Remove ith/Nth Occurrence of Given Word in List
  4. Python Program to Sort List in Ascending and Descending Order
  5. Python to Find the Differences of Two Lists
  6. Python to Find Minimum and Maximum Elements of List
  7. Python Programs to Split Even and Odd Numbers in Separate List
  8. Python Program to Create Two Lists with First Half and Second Half Elements of Given List
  9. Python Program to Swap Two Elements in a List
  10. Python Program to Reverse List
  11. How To Select Random Item From A List In Python
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments