Insert an element at the nth position in a list
by
Jiffin Joachim Gomez on 24th February 2017
This is a Python script to insert an element at the nth position in 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 a new element must be made. Then it will check if the entered position is valid or not. If it is valid then the program will ask the user to input the element to be inserted. The
insert() function is used to insert the element to the list.
list = input('Enter the list elements : ').split()
elem = input('Enter the element to be inserted: ')
pos = int(input('Enter the position where the element is to be inserted: '))
len = len(list)
if(pos >= 1 and pos <= len):
print("The List before insertion", list)
list.insert(pos-1, elem)
print("The List after deletion", list)
else:
print("Element position is invalid")
Program Output
Enter the list elements : 5 4 3 2 6
Enter the element to be inserted: 1
Enter the position where the element is to be inserted: 2
The List before insertion ['5', '4', '3', '2', '6']
The List after deletion ['5', '1', '4', '3', '2', '6']
>>>
Post a comment
Comments