This post is to show how to remove duplicate entries in a List.
Create an empty list and we name it new_list.
In [1]: new_list = []
We iterate a range of integers and assign it to this new_list.
In [2]: for items in range(1,6):
...: new_list += [items]
...:
Show what is inside this list
In [3]: new_list
Out[3]: [1, 2, 3, 4, 5]
We iterate another range of integers where there are duplicates into the same new_list
In [4]: for new_items in range(7):
...: new_list += [new_items]
...:
This show the new_list has duplicate entries
In [5]: new_list
Out[5]: [1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]
Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
Then, convert the dictionary back into a list.
In [6]: new_list = list(dict.fromkeys(new_list))
In [7]: new_list
Out[7]: [1, 2, 3, 4, 5, 0, 6]
In [8]:
No comments:
Post a Comment