Remove duplicates from list.
Python: Remove duplicates from list. |
You can remove duplicates from list in a few ways which I'll show in this post.
Iterating with for and removing duplicates.
li = [1,1,2,3,4,3]pos = 0 will store the index of element which occur more than once in a list what program does check in for loop with if statement and count method:
pos= 0
for i in li:
if li.count(i) > 1:
pos = li.index(i)
for q in li[pos+1:]:
if q == i:
li.remove(q)
print(li)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
[1, 2, 4, 3]
if li.count(i) > 1:
Next line does store the index of the element which occure more than once.
pos = li.index(i)Line below initiates another for loop but from the index +1 from stored element which has duplicates and if duplicates are found these duplicates are removed.
if q == i:
li.remove(q)
Create new list and check if element occur in a new list.
li = [1,1,2,3,4,3]
li2 = []
for i in li:
if i not in li2:
li2.append(i)
print(li2)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
[1, 2, 3, 4]
li2=[] is new list to which will be added elements after checking if if those elements are already not in the list.
To do this for loop iterates over the list and if statement has a condition: if element not in li2 add this element to new list li2.
To do this for loop iterates over the list and if statement has a condition: if element not in li2 add this element to new list li2.
Remove duplicates in list with sets.
Sets are data types similarly to list and used to store collections data with no duplicate element what makes them perfect to remove duplicates from the list.
li = [1,1,2,3,4,3]
s = set(li)
li2 = list(s)
print(li2)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
[1, 2, 3, 4]
s = set(li)
Variable s stores a set which is copy of the list li but as mentioned earlier sets do not store the duplicates so any duplicates are removed.
li2 = list(s)
li2 is a new list of set s made with list() method.Here is a shorter version of above operation.
li = [1,1,2,3,4,3]
li2= list(set(li))
print(li2)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
[1, 2, 3, 4]
You
can donate me so I can afford to buy a coffee myself, this will help me
to keep going and create more content that you find interesting.
Many thanks
Stay Happy and Keep Coding :-)
Stay Happy and Keep Coding :-)
Comments
Post a Comment