Python provides slicing functionality for lists, but for this question, you will
ID: 3844587 • Letter: P
Question
Python provides slicing functionality for lists, but for this question, you will implement your own function capable of producing list slices The function should be called slice and take the following three arguments in this specific order: 1. A list, source, which the slice will be created from. This list cannot be modified by your function. A positive integer, start, representing the starting index of the slice you will create. If this value is not in the range [0, len(list)-1], your function should return an empty list. 3. A positive integer, end, representing the ending index of the slice you will create. If this value is not in the range [start, len(list-1], your function should return an empty list. If the parameter values are acceptable, your function will return a list that contains the items from source beginning at the index start and ending at the index end (inclusive). This is different from the Python slice operator, as the item at the index end is also included in the new list. Examples: mylist = [" A", " B", " C", " D", " E", " F", " G", " H " l", " J"] slice(mylist, 0, 9) should be [A", " B", " C", " D", " E", " F", " G", " H", " l'", " J"] slice(mylist, 3, 4) should be [" D", " E"] slice (mylist, 4, 3) should be [] slice(mylist, 3, 8) should be [" D", " E", " F", " G", " H", " l"] slice (mylist, 4, 4) should be [" E"] Save your code is a file called slice.py and add it to your submission zipExplanation / Answer
#slice.py #ORIGINAL LIST source = ["A","B","C","D","E","F","G","H","I","J"] #SLICE FUNCTION def slicelist(mylist,x,y): newlist = [] while True: #CHECKS IF VALUE IS ACCEPTABLE IN LIST if (x < 0) or ( x > (len(mylist))-1 ): break #CHECK IF VALUE IS ACCEPTABLE IN LIST if (y < 0) or ( y > (len(mylist))-1 ): break #FOR LOOP ADDS ITEMS IN RANGE TO newList from original list for i in range(x, y+1): newlist.append(mylist[i]) break #return newList return newlist #ERROR CHECK FOR STARTING VALUE start = input("Enter starting index: ") while True: if start.isdigit()==False: start = input("Invalid Input. Please enter an integer: ") else: break #ERROR CHECK FOR ENDING VALUE end = input("Enter ending index: ") while True: if end.isdigit()==False: end = input("Invalid Input. Please enter an integer: ") else: break #PRINT THE SLICED LIST WITH STARTING AND ENDING VALUES print(slicelist(source,int(start),int(end)))Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.