How To Remove Duplicates From List In Python With Code?

Python is the fastest-growing language in the world and it’s not just hype, it has some of the best features that any other programming language.

The built-in Python libraries provide some of the most useful and resources across various platforms.

If you ever got stuck somewhere then no issues, the python community is awesome always ready to push you beyond with all that said let’s see how to remove duplicates from a list in python.

List is one of the 4 built-in collection data types in python the other 3 are tuple, set and dictionary.

List acts like an array, it stores data in an ordered manner meaning the first element is at 0th position the second element is at 1st position, and so on.

You can read each and everything about python here.

With just a few lines of code, you can easily remove duplicates from the list in python.

remove duplicates from list in python

You can copy the code here.

L1 = [‘Java’, ‘Python’, ‘Javascript’, ‘C++’,
‘Java’, ‘C’, ‘Swift’, ‘C#’, ‘Kotlin’]
L2 = []
for i in L1:
if i not in L2:

The code is as simple as printing hello world in any other programming language.

  1. We have taken a list L1 with some values
  2. On line 3 we have created an empty list L2 where we will store our results.
  3. On line 4 we have applied for a loop. We have iterated over each element of list L1 and assigned each element to variable ‘i’.
  4. Next, we have an if condition where it is trying to say if an element in ‘i’ is not in L2 then put the content of ‘i’ in L2.
  5. This appends method just simply adds a new element at the end of the list
  6. Note that when L2 gives ‘Java’ element a second time to ‘i’ and ‘i’ checks if that element is in L2 or not it finds yes that element is already inside L2 so does not execute or go inside if the condition it simply iterates over next item in for loop.
  7. After successful completion of for loop, we have simply printed list L2.

Source link