Remove First or Nth Element from List in Django

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]

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.

Similar Stories