Remove item in list C#
Ngày đăng:
09/11/2021
Trả lời:
0
Lượt xem:
121
The remove() method removes the first matching element (which is passed as an argument) from the list. Show Example# create a list prime_numbers = [2, 3, 5, 7, 9, 11]# remove 9 from the list prime_numbers.remove(9) # Updated prime_numbers List print('Updated List: ', prime_numbers) # Output: Updated List: [2, 3, 5, 7, 11]Syntax of List remove()The syntax of the remove() method is: remove() Parameters
Return Value from remove()The remove() doesn't return any value (returns None). Example 1: Remove element from the list# animals list animals = ['cat', 'dog', 'rabbit', 'guinea pig']# 'rabbit' is removed animals.remove('rabbit') # Updated animals List print('Updated animals list: ', animals)Output Example 2: remove() method on a list having duplicate elementsIf a list contains duplicate elements, the remove() method only removes the first matching element. # animals list animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']# 'dog' is removed animals.remove('dog') # Updated animals list print('Updated animals list: ', animals)Output Here, only the first occurrence of element 'dog' is removed from the list. Example 3: Deleting element that doesn't exist# animals list animals = ['cat', 'dog', 'rabbit', 'guinea pig']# Deleting 'fish' element animals.remove('fish') # Updated animals List print('Updated animals list: ', animals)Output Traceback (most recent call last): File ".. .. ..", line 5, in animal.remove('fish') ValueError: list.remove(x): x not in listHere, we are getting an error because the animals list doesn't contain 'fish'.
|