Removing items from the list

 Removing items from the list :

Python provides several methods to remove list items

1. pop(): Deletes an item at a specific index.

2. remove(): Removes the first occurrence of a value.

3. clear(): Empties the list of all items.

Let's explore each, beginning with pop().


Pop Method()

Let's say you have a list with items 'a', 'b', and 'c', and you want to

remove an item at index 2. The list pop method can help you remove a

list item at a specific index. Here's how.


my_list = ['a', 'b', 'c']

my_list.pop(2)

print(my_list)


explanation

  • my_list = ['a', 'b', 'c']: Here, we make a list named my_list with three items: 'a', 'b', and 'c'.

  • my_list. pop (2): This line removes the item at the 2nd index, which is 'c'.

  •  print (my_list): This shows the updated list.

Output :

[ʹaʹ, ꞌbʼ]


Using remove()

What if you have a list with items 'a', 'b', and 'c', and you want to remove

the item 'b' from this list? You can use the list remove method to take

out a specific item by its value.


my_list = ['a', 'b', 'c']

my_list.remove('b')

print(my_list) 

explanation

  • my_list = ['a', 'b', 'c']: Here, we make a list named my_list with threeitems: 'a', 'b', and 'c'.

  • my_list. remove ('b'): This line removes the item 'b' from the list.
  • print (my_list): This shows the updated list.

Output :

['a', 'c']


clear() Method

Let's say you want to remove all the items of the list. You can use the

clear method for that.


my_list = ['a', 'b', 'c']

my_list.clear()

print(my_list)

explanation

  • my_list = ['a', 'b', 'c']: Here, we make a list named my_list with three items: 'a', 'b', and 'c'.
  • my_list. clear (): This line removes all the items of the list.
  • print (my_list): This shows the updated list.
Output :
[]


  • You have to must try in your python compiler use idle avoid online compilers to Errors

Post a Comment

0 Comments