Remove First or Nth Element from List in Django

Published on Sep 10, 2022

Hey artisans, in this artical we are going to learn how to remove first or n element from list in Django. We can remove element from lits using remove , del and pop methods.

Table of Contents

Remove()

The remove removes the first matching value, not a specific index. It takes value, removes the first occurrence, and returns nothing.

views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    myList = [1, 2, 3, 4, 5, 6]

    myList.remove(1)

    print(myList)

    return HttpResponse('')

Output:

[2, 3, 4, 5, 6]

Del()

The del removes the item at a specific index. It takes index, removes value at that index, and returns nothing.

views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    myList = [1, 2, 3, 4, 5, 6]

    del myList[0]

    print(myList)

    return HttpResponse('')

Output:

[2, 3, 4, 5, 6]

Pop()

The pop removes the item at a specific index and returns it. It takes index (when given, else take last), removes value at that index, and returns value.

views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    myList = [1, 2, 3, 4, 5, 6]

    myList.pop(0)

    print(myList)

    return HttpResponse('')

Output:

[2, 3, 4, 5, 6]

Comments (0)