Python List Functions | del(), remove(), pop() and clear() functions in Python
Python List/Array Functions (Methods)
Python has a set of built-in
methods that you can use on lists/arrays.
Method |
Description |
append() |
Adds an element at the end of the list |
clear() |
Removes all the elements from the list |
copy() |
Returns a copy of the list |
count() |
Returns the number of elements with the specified value |
extend() |
Add the elements of a list (or any iterable), to the
end of the current list |
index() |
Returns the index of the first element with the
specified value |
insert() |
Adds an element at the specified position |
pop() |
Removes the element at the specified position |
remove() |
Removes the first item with the specified value |
reverse() |
Reverses the order of the list |
sort() |
Sorts the list |
Del() |
Delete the element at the specified position |
Del()
Definition and Usage
The del()
method work on index number its removes
the element at the specified position.
Syntax
Del list(pos)
Parameter
Values
Optional. A number specifying the position of the element you
want to remove, default value is -1, which returns the last item
Example
Remove the second element of the fruit
list:
fruits = ['apple', 'banana', 'cherry']
del fruits(1)
print (fruits)
pop()
Definition and Usage
The pop()
method also work on index number its removes
the element at the specified position.
Syntax
list.pop(pos)
Parameter
Values
Optional. A number specifying the position of the element you
want to remove, default value is -1, which returns the last item
Example
Remove the second element of the fruit
list:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print (fruits)
Example
Return the removed element:
fruits = ['apple', 'banana', 'cherry']
x = fruits.pop(1)
Note: The pop() method returns removed value.
Example
Return the removed element:
fruits = ['apple', 'banana', 'cherry']
print (fruits.pop(1))
print (fruits)
remove()
Definition and Usage
The remove()
method removes the first occurrence of
the element with the specified value.
Syntax
list.remove(elmnt)
Parameter
Values
Required. Any type (string,
number, list etc.) The element you want to remove
Example
Remove the "banana" element of the fruit
list:
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
clear()
Definition and Usage
The clear()
method removes all the elements from a
list.
Syntax
list.clear()
Parameter
Values
No parameters
Example
Remove all elements from the fruits
list:
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
Post a Comment