How to Remove Duplicate Values from List in Django?

Published On: 26/07/2022 | Category: Django Python

Hi Dev,

Now, let's see tutorial of django remove duplicates from list. you can see how to remove duplicate values from list in django. I would like to share with you how to avoid duplicate values in list django. This tutorial will give you simple example of django delete duplicates in list of lists. you will do the following things for django remove duplicates in list.

There are several ways to delete duplicate values from the list in python. we will use set() and dict() functions to remove duplicates elements from list. so let's see the below examples.

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Example : 1 views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):

    myList = ['one', 'two', 'two', 'three', 'four', 'five', 'five']
  
    # Remove Duplicate Value from List
    newList = list(set(myList))
      
    print(newList)
    
    return HttpResponse('')
Output
['three', 'two', 'four', 'five', 'one']
Example : 2 views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):

    myList = [1, 2, 3, 4, 4, 5, 5]
  
    # Remove Duplicate Value from List
    newList = list(dict.fromkeys(myList))
      
    print(newList)

    return HttpResponse('')
Output
[1, 2, 3, 4, 5]

I Hope It will help you....