Add and Remove items from List

Add and Remove items from List

Instructor-svgAl-Mamun Sarkar
Apr 10 , 2021

We can add items using append and insert class. In this section, I will show you how we can add and remove items from a list. 

 

Add item at the last of the list:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.append("seven")
print(numbers)

Output:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.append("seven")
print(numbers)

 

Insert item at a specific index:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.insert(1, "item")
print(numbers)

Output:

['one', 'item', 'two', 'three', 'four', 'fine', 'six']

 

Extend List in Python:

one = ['one', 'two', 'three']
two = ['four', 'fine', 'six']
one.extend(two)
print(one)

Output:

['one', 'two', 'three', 'four', 'fine', 'six']

 

Add two List in Python:

one = ['one', 'two', 'three']
two = ['four', 'fine', 'six']
print(one + two)

Output:

['one', 'two', 'three', 'four', 'fine', 'six']

 

Remove Items from a List:

 Remove by item value:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.remove("three")

Output:

['one', 'two', 'four', 'fine', 'six']

 

 Remove the last item:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.pop()

Output:

['one', 'two', 'three', 'four', 'fine']

 

 Remove an item by index:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.pop(1)

Output:

['one', 'three', 'four', 'fine', 'six']

 

 Remove an item by index using del:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
del numbers[0]

Output:

['two', 'three', 'four', 'fine', 'six']

 

Clear the List (Delete all items):

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
numbers.clear()
print(numbers)

Output:

[]

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram