I'm trying to write a function that will slice a list between two given values. If the stop value exceeds the list bounds, the stop value is the length of the list. If the start value exceeds the list bounds, I want to return an empty list. If the start value is less than the stop value, I want to return an empty list. I do not want to use any built-in functions or methods other than range()
and list.append()
The code that is calling the function is:
str_list = ['s', 'h', 'r', 'u', 'g', 'g', 'e', 'd']
print("\nget_slice Test")
my_slice = list_function.get_slice(str_list, 2, 100)
print(list_function.to_string(str_list))
print(list_function.to_string(my_slice))
my_slice = list_function.get_slice(str_list, 6, 1)
print(list_function.to_string(my_slice))
my_slice = list_function.get_slice(str_list, 2, 5)
print(list_function.to_string(str_list))
print(list_function.to_string(my_slice))
The output I want to produce is:
get_slice Test
List is: s, h, r, u, g, g, e, d
List is: r, u, g, g, e, d
List is:
List is: s, h, r, u, g, g, e, d
List is: r, u, g
I'm defining the function as:
def get_slice(my_list, start, stop):
I've tried my_list = my_list[start:stop]
but I get a 'NoneType' object is not iterable error. I also wanted to try using for k in range(0, length(my_list)):
, as it was suggested that I use range()
, however I can't think of a way that could be used for this function just yet.
Any assistance with this would be greatly appreciated.