Given a list, start and end index, we have to create a list from specified index of the list in Python.
Example 1:
Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end = 4
Logic to create list with start and end indexes:
List1 = list[start: end+1]
Output:
list1: [20, 30, 40, 50]
Example 2:
Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end = 6
Logic to create list with start and end indexes:
list1 = list[start: end+1]
Output:
Invalid end index
Logic:
- Take a list, start and end indexes of the list.
- Check the bounds of start and end index, if start index is less than 0, print the message and quit the program, and if end index is greater than the length-1, print the message and quit the program.
- To create a list from another list with given start and end indexes, use list[n1:n2] notation, in the program, the indexes are start and end. Thus, the statement to create list is list1 = list[start: end+1].
- Finally, print the lists.
Program:
Output
Test with the invalid index
Size of the list is 6, and indexes are from 0 to 5, in this example the end index is invalid (which is 6), thus program will print "Invalid end index" and quit.
Note: Program may give correct output if end index is greater than the length-1 of the list. But, to execute program without any problem, we should validate the start and end index.
Output
need an explanation for this answer? contact us directly to get an explanation for this answer