Python By Example

Delete n-th element of a list

by Jiffin Joachim Gomez on 24th February 2017

This is a Python script to delete nth element of a list. At first the program prompts the user to input the list elements. The user inputs the list elements separated by a space character. The split() function is used to split the input string into list elements and assign it to a variable. The program then asks the user to enter the nth position where the deletion must be made. Then it will check if the entered position exists or not. If it exists then the element at that position is deleted using the del statement.

list = input('Enter the list elements : ').split()

pos = int(input('Enter the position of the element to be deleted: '))
len = len(list)
if(pos >= 1 and pos <= len):
    print("The List before deletion", list)
    del list[pos-1]
    print("The List after deletion", list)
else:
    print("Element position is invalid")    

Program Output


Enter the list elements : 5 8 3 9 2
Enter the position of the element to be deleted: 2
The List before deletion ['5', '8', '3', '9', '2']
The List after deletion ['5', '3', '9', '2']
>>> 

Post a comment

Comments

Nothing yet..be the first to share wisdom.