How to Remove Duplicates from a list in PythonWhen an element occurs more than once in a list, we refer to it as a duplicate. In this tutorial, we will learn different methods of removing these duplicates from a list in Python.
Let us discuss each one of them in detail. The Basic ApproachIn the first method, we will discuss the basic approach of removing duplicates from the list using Python. Output: The initialized list is [12, 15, 11, 12, 8, 15, 3, 3] The resultant list after removing duplicates is [12, 15, 11, 8, 3] Explanation So, now it’s time to have a glance at the explanation of the above program.
In the second program, we will make use of list comprehension to meet our objective. Using List ComprehensionThe following program illustrates the same- Output: The initialized list is [12, 15, 11, 12, 8, 15, 3, 3] The resultant list after removing duplicates is [12, 15, 11, 8, 3] Explanation Let’s understand what we have done in the above program-
In the third approach, we will see how set() can be used to obtain a list of distinct elements. Using Set()The program given below shows how it can be done- Output: The initialized list is [12, 15, 11, 12, 8, 15, 3, 3] The resultant list after removing duplicates is [12, 15, 11, 8, 3] Explanation Let’s try and understand what happened here,
Using enumerate()Now let’s see how enumerate() can be used to meet our objective. The following program illustrates the same- Output: The initialized list is [12, 15, 11, 12, 8, 15, 3, 3] The resultant list after removing duplicates is [12, 15, 11, 8, 3] Explanation
Finally, in the last program we will see how OrderedDict can be used to remove duplicates from list using Python. Using OrderedDictThe program given below shows how it can be done- Output: The initialized list is [12, 15, 11, 12, 8, 15, 3, 3] The resultant list after removing duplicates is [12, 15, 11, 8, 3] Explanation
ConclusionIn this tutorial, we explored and learned some interesting methods to remove duplicates from a list in Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263377.html