How To Clear or Remove Elements From a list in Python
Sometimes When We add Elements in a list it becomes Troublesome to remove elemnts from the list so that we can use them again in our code or console.So to remove Elements from a list there are 3 ways
1)Re initialization of List
2)Using Pop function
3)Using del function
4)Using Remove function
1)Re initialization
Reintialing the list clears up the whole list for reuse of the elements or variables
so if my list is full of elements
eg. A=[1,2,3,4,5,6]
and i want A as an empty list we simply re initialize a list
A=[]
gives us an Empty list which clears up the whole variable
2)Pop function
It removes the last element if unspecified or removes the specified indexed element from a list or array
so if my list is full of elements
eg. A=[1,2,3,4,5,6]
A.pop()
6
numbers = arr.array('i', [10, 11, 12, 12, 13])
print(numbers.pop(2))
# Output: 12
print(numbers) #
Output: array('i', [10, 11, 13])
To pop out lists
numbers = arr.array('i', [10, 11, 12, 12, 13])
print(numbers.pop(2))
# Output: 12
print(numbers) #
Output: array('i', [10, 11, 13])
To pop out lists
B=[1,[2,3]]
B.pop()
[2, 3]
will remove only one element or a list inside a list
so we iterate the list while the length og list becomes 0 and pop all elements out of our listA [1,2,3,4,5,6]
while(len(A)>0):A.pop()
6
5
4
3
2
1
B=[1,[2,3],[4,5],6]
while(len(B)>0):B.pop()
6
[4, 5]
[2, 3]
1
3)Using del function
Delete function is used to permanently delete something from the memory.
If there is a list which we want to remove all elements using del function we write del then name of variable and slicing.
A=[1,2,3,4,5,6]
del A[::] #does slicing of all elements of a list
print(A)
[]
if we simply do a del function without slicing it removes that variable from memory space.
A=[1,2,3,4,5,6]
del A
print(A)
Traceback (most recent call last):
File "<pyshell#176>", line 1, in <module>
A
NameError: name 'A' is not defined
I know why would we delete the whole variable in the first place it can be used to free the memory and reallocate it to some other memory other than that we can slice the values however we want.
4) Remove
This function removes from a specific Array in the function.
Note - it only removes the first found occurance.
numbers = arr.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers)
# Output: array('i', [10, 11, 12, 13])
Final thoughts
You can use any of the following methods to remove an element from a list or an array it depends on what logic you actually want to achieve from it.
Usually lists are much more flexible than arrays. They can store elements of different data types including string. Also, lists are faster than arrays. And, if you need to do mathematical computation on arrays and matrices, you are much better off using something like NumPy library like numpy arrays or Pandas library dataframes.
Comments
Post a Comment