Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
92 views
in Computer by (51.9k points)
closed by

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.

1 Answer

+1 vote
by (49.5k points)
selected by
 
Best answer
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]

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...