I am trying to add an item, insert and sort to a list without using built in functions such as .append or insert or extend I have to write def function. I want to add maria to the student name list. and write another def function to sort it using index.
studentname=["kay","joe"]
def addname(studentname):
newlist = studentname[0]
for i in range(name):
name=input("enter name")
newlist =studentname +[name]
print(studentname)
addname(newlist)
Here is the completed code for this problem. Though the question is not completely clear, I understood that the major goals are to add an element to list without using append or insert and sort a list without using built in sort methods. So I have updated the code to fulfil above requirements and a main method that asks the user to enter student names, add to the list and display it in sorted order when student enter ‘exit’ to finish the entry process. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code
''' method to add a name to a list without using append, insert or extent''' def addName(student_list, name): #using += operator, appending name to student_list and storing in student_list student_list+=[name] ''' method to sort the student list ''' def sortList(student_list): #using bubble sort algorithm for i in range(len(student_list)): for j in range(len(student_list)-1): #comparing elements at index j and j+1 if student_list[j]>student_list[j+1]: #swapping elements at index j and j+1 student_list[j],student_list[j+1]=student_list[j+1],student_list[j] ''' main method for testing ''' def main(): #creating a list with initial values 'kay' and 'joe' studentnames = ["kay", "joe"] #loops infinitely while True: #reading a name from user name=input('Enter a name to add or "exit" to finish: ') #if input if 'exit', exiting the loop if name=="exit": break #otherwise adding the name to list using addName method addName(studentnames,name) #after the loop, sorting the list sortList(studentnames) #printing the sorted list. print(studentnames) #running main() main()
#output
Get Answers For Free
Most questions answered within 1 hours.