हिंदी

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.

Advertisements
Advertisements

प्रश्न

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.

संक्षेप में उत्तर
Advertisements

उत्तर

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]
shaalaa.com
Lists Methods and Built-in Functions in Python
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 9: Lists - Exercise [पृष्ठ २०६]

APPEARS IN

एनसीईआरटी Computer Science [English] Class 11
अध्याय 9 Lists
Exercise | Q 7. | पृष्ठ २०६
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×