CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Write a program to read a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted. Write a user defined function to insert the element at the desired position in the list.

Open in App
Solution

Program:
def addElements(list1):
newList = list1

#Asking the user if he want to add any element to the list
inp = input("Do you want to add any new element to the list? (Y/N) ")

#if user input is yes
if(inp == 'Y' or inp == 'y'):
elem = int(input("Enter the element: "))
index = int(input("Enter the index at which you would like to add the element: "))

#Using insert() function to add the element at particular index
newList.insert(index,elem)
print("***Element added***")
addElements(newList) #Calling the addElement function again to check if new element should be added
return newList

#Defining empty list
list1 = []

#Getting input for the number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? "))

#Taking the input from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)

#Printing the list
print("The list entered is:",list1)

#Calling the addElement function to get a confirmation about adding the element to the list and then returning the modified list
modList = addElements(list1)
print("The modified list is: ",modList)

ā€‹
OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 33
Enter the elements: 44
Enter the elements: 55
Enter the elements: 66
Enter the elements: 77
Enter the elements: 12
The list entered is: [33, 44, 55, 66, 77, 12]
Do you want to add any new element to the list? (Y/N) y
Enter the element: 11
Enter the index at which you would like to add the element: 0
***Element added***
Do you want to add any new element to the list? (Y/N) n
The modified list is: [11, 33, 44, 55, 66, 77, 12]

flag
Suggest Corrections
thumbs-up
2
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Organisation of Data
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon