estudarpara
search
  • Q&A
  • Listas principais
  • Top produtos
  • Tag
  • Q&A
  • Listas principais
  • Top produtos
  • Tag

What are the two methods for removing items from a list in Python?

11 mêss atrás
Comentários: 0
Visualizações: 177
Share
Like

In this python tutorial, we look at all the different methods you could use to remove item from list in python. We also break down which methods are best suited for each use case.

Show
  • Table of Contents
  • Removing items from list - Python
  • Using Value to remove items
  • Syntax of remove():
  • Parameters:
  • Code to remove item from list by value:
  • Remove item from list by Index:
  • Syntax of pop()
  • Parameters:
  • Code to remove item from list by index:
  • Remove item from list using del:
  • Syntax of del:
  • Code to remove items using del
  • Limitations and Caveats:
  • Delete an element from a list using the del 
  • Delete an element from a List using pop() 
  • Remove an item from a list using discard() method
  • Remove an item from a list using filter() method

Table of Contents

  • Removing items from list python
  • Using Value to remove items
  • Remove item from list by Index
  • Remove item from list using del
  • Limitations and Caveats

Removing items from list - Python

Since lists are mutable, python comes built with a few list methods that can be used to remove items from lists. Some of these methods are pop(), remove(), clear(), etc.

Although all these methods can be used to remove items from lists in python they are built to cater to different use-cases, we discuss them in detail below.

Apart from these list methods, the del() method can also be used to remove items in a list.

Using Value to remove items

In this method, we remove items from the list based on their value. We achieve this by using the remove() list method. This method is quite straightforward, however, it is case sensitive and only removes the first occurrence of the value.

Passing the value in the wrong case would return a ValueError..

Syntax of remove():

list.remove(value) Here list refers to the name of the list.

Parameters:

value - The element that you want to remove.

Code to remove item from list by value:

list1 = ["Hire","Hire", "the", "top", 10, "python","freelancers"] list1.remove("Hire") print(list1) #Output - ['Hire', 'the', 'top', 10, 'python', 'freelancers']

As you can see, only the first occurrence of "Hire" was deleted. You could also try breaking the code trying to remove a lower case "hire".

Remove item from list by Index:

Since lists are ordered, each item can be referred to using its index. These indexes refer to a unique value and hence it can be used to remove items from a list in python.

For this, we use the pop() methods. Another use case of pop() is to remove and return the deleted item. In such cases pop() is used instead of remove(). Also, note that if no index is passed as a parameter, pop() removes and returns the last item.

Syntax of pop()

list.pop(index) Here list refers to the name of the list.

Parameters:

index - Optional, the index of the item you want to remove.

Returns:

Return the item removed from the list, in case you do not pass an index the last value is returned.

Code to remove item from list by index:

list1 = ["Hire", "the", "top", 10, "python","freelancers"] removed_item = list1.pop(0) print(list1) print(removed_item) #Output - ['the', 'top', 10, 'python', 'freelancers'] #Output - "Hire"

Remove item from list using del:

del is another way to remove items from a list in python. Although this is not a list method it does come with a unique use case.

Similar to pop(), del also removes items using their index. However, what’s unique is that it can be used to remove multiple items at a time.

Syntax of del:

del object_name

Passing the name of the list followed by the index or an index range after del will remove the items from the list in python.

Code to remove items using del

list1 = ["Hire", "the", "top", 10, "python","freelancers"] del list1[0] print(list1) #Output - "['the', 'top', 10, 'python', 'freelancers']"

And if you are looking to remove multiple items from a list, adding an index range would help you achieve this.

list1 = ["Hire", "the", "top", 10, "python","freelancers"] del list1[0:4] print(list1) #Output - ['python', 'freelancers']

Limitations and Caveats:

  • While trying to remove items from a list in python using remove(), a ValueError is returned if the parameter cannot be found
  • The pop() only allows int values to be passed as a parameter, and an IndexError is returned if the index is out of range

Python Lists have various in-built methods to remove items from the list. Apart from these, we can also use different methods to remove an element from the list by specifying a position using Python.

Delete an element from a list using the del 

The Python del statement is not a function of List. Items of the list can be deleted using the del statement by specifying the index of the item (element) to be deleted. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

del lst[1]

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

In this method, we are using list comprehension. Here, we are appending all the elements except the elements that have to be removed.

list1 = [1, 9, 8, 4, 9, 2, 9]

print ("original list : "+ str(list1))

list1 = [ele for ele in list1 if ele != 9]

print ("List after element removal is : " + str(list1))

Outputoriginal list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [1, 8, 4, 2]

We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst.remove('Orchids')

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

Delete an element from a List using pop() 

The pop() is also a method of listing. We can remove the element at the specified index and get the value of that element using pop(). 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

a = lst.pop(1)

print("Item popped :", a)

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] Item popped : Orchids After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

Remove an item from a list using discard() method

In this method, we convert a list into a set and then delete an item using the discard() function. Then we convert the set back to the list.

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst = set(lst)

lst.discard('Orchids')

lst=list(lst)

print("List after element removal is :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] List after element removal is : ['Lily', 'Carnations', 'Iris', 'Rose', 'Lavender']

Note: Since the list is converted to a set, all duplicates will be removed and the ordering of the list cannot be preserved.

Remove an item from a list using filter() method

In this method, we filter the unwanted element from the list using the filter() function. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst1 = filter(lambda item: item!='Orchids',lst)

print("List after element removal is :", list(lst1))

Output('Original List is :', ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']) ('List after element removal is :', ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations'])


Q&A What

Postagens relacionadas

When to check blind spot driving test
When to check blind spot driving test

What sentence best conveys the speaker’s message?
What sentence best conveys the speaker’s message?

What do you call the events that have outcomes in common
What do you call the events that have outcomes in common

What makes an airplane in level flight with constant speed?
What makes an airplane in level flight with constant speed?

What is a straight reduction in price on purchases during a stated period of time or of larger quantities?
What is a straight reduction in price on purchases during a stated period of time or of larger quantities?

Three six-sided dice are rolled. what is the probability that at least one comes up with a 5 or 6?
Three six-sided dice are rolled. what is the probability that at least one comes up with a 5 or 6?

When objects are in thermal equilibrium the heat exchange between two objects is?
When objects are in thermal equilibrium the heat exchange between two objects is?

A number from 1 to 11 is chosen at random what is the probability of choosing an odd number
A number from 1 to 11 is chosen at random what is the probability of choosing an odd number

What measurement is 1/3 of a tablespoon?
What measurement is 1/3 of a tablespoon?

What is the equation of the line that passes through the point (8,-6)(8,−6) and has a slope of 0?
What is the equation of the line that passes through the point (8,-6)(8,−6) and has a slope of 0?

Onde vai passar corinthians x bragantino
Onde vai passar corinthians x bragantino

Quem é o Calisto da novela O Cravo e A Rosa?
Quem é o Calisto da novela O Cravo e A Rosa?

Qual o melhor horário para tomar picolinato de cromo para emagrecer?
Qual o melhor horário para tomar picolinato de cromo para emagrecer?

Quem recebe pensão vitalícia tem direito ao décimo terceiro
Quem recebe pensão vitalícia tem direito ao décimo terceiro

Como terminou o jogo do Flamengo e Atlético?
Como terminou o jogo do Flamengo e Atlético?

O que é plano de ensino
O que é plano de ensino

Que hora começa o power couple
Que hora começa o power couple

Na escola italiana desenvolveram se várias correntes de pensamento contábil
Na escola italiana desenvolveram se várias correntes de pensamento contábil

Quais são os benefícios do sulfato de magnésio?
Quais são os benefícios do sulfato de magnésio?

Como ligar para uma agência do Banco do Brasil?
Como ligar para uma agência do Banco do Brasil?

Publicidade

ÚLTIMAS NOTÍCIAS

Which type of conflict is best described as interpersonal opposition based on dislike or disagreement among individuals?
11 mêss atrás . por KnownHierarchy
How do you mix short acting and intermediate insulin?
11 mêss atrás . por UntrainedSnack
Can u pin someone on Snapchat on Android?
11 mêss atrás . por FullHardship
What total appears in row 6 of your query result?
11 mêss atrás . por UnmovedRatification
Subcutaneous injection maximum volume Pediatric
11 mêss atrás . por AppreciativeStillness
Says that behavior that is rewarded will increase, while behavior that is punished will decrease.
11 mêss atrás . por IneffableInvasion
Which psychological changes is associated with aging?
11 mêss atrás . por IncredulousFertilization
Which of the following stressors is likely to produce less strain than the other stressors?
11 mêss atrás . por MigratoryOunce
How many Litres of water must be added to 75 Litres of milk that contains 13% water to make it 25% water in it?
11 mêss atrás . por MortalRoadblock
What sum of money will amount to 72900 at 8% per annum for 2 years if the interest is payable annually?
11 mêss atrás . por SuspendedUnification

Toplistas

#1
Top 8 resultado do jogo do bicho de hoje das 14 2022
1 anos atrás
#2
Top 5 treino para academia masculino 2022
1 anos atrás
#3
Top 6 comida tipica dos negros 2022
1 anos atrás
#4
Top 6 como ser ponto de coleta mercado livre 2022
1 anos atrás
#5
Top 7 sonhar com criança da o quê no jogo do bicho 2022
1 anos atrás
#6
Top 7 com quanto tempo escuta o coração do bebe 2022
1 anos atrás
#7
Top 8 resultado do jogo do bicho 14 30 2022
1 anos atrás
#8
Top 5 cha dos famosos para emagrecer 2022
1 anos atrás
#9
Top 7 receita de brownie sem ovo 2022
1 anos atrás
#10
Top 7 tua palavra é lampada para os meus pes senhor 2022
1 anos atrás

Publicidade

Populer

Publicidade

Sobre

  • Sobre
  • Apoiar
  • Carreiras
  • Publicidade

Jurídica

  • Política de Privacidade
  • Termos de serviços
  • Política de Cookies

Ajuda

  • Base de conhecimento
  • Remova uma pergunta
  • Apoiar

Social

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
hometrzhko

direito autoral © 2023 estudarpara Inc.