Program to remove the element at given index using Python

by | Feb 9, 2021 | Python Programs

Introduction

In this section of python programming, we will understand the code to eliminate the given element from the list on the basis of given index.

Program to remove the element at given index using Python

Program

def remove(list, element, index):
    if 0 <= index <= len(list) - 1:
        for i in range(0,len(list)):
            if list[i] == element:
                if i == index:
                    del(list[i])
                    return list
                else:
                    return "Element is not found at given index!"
    else:
        return "Give the valid index point!"
list = ['is', 'on', 'at', 'is']
element = 'at'
index = 2
print(remove(list,element,index))

Output

Program to remove the element at given index using Python Output

Explanation

In the above python code, we have created a list with few elements, a variable elements which stores the string value to be eliminated and a variable index which stores the integer value to locate the position in list. Our task is to remove the element ‘at’ if it exists at index 2, remember the indexing in list starts with 0. So basically we will look at position 3 of the list and check if the given element is there or not.

The function remove() will check for the requirement and if it satisfies it returns the updated list after deletion of element otherwise it will return “Element is not found at given index!”.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.