I have been searching how to do this for the past while but can't seem to find anything that answers my problem or its idea and code is too complex for me to understand as a complete beginner. So basically this is the task I have to do:
Write a function all sublists(lst) that for a list lst returns as its result a list of all of sublists of lst. A sublist is a list containing a contiguous portion of the original i.e. comprising zero or more consecutive elements from the orginal.
For example, for the list [1, 2, 3] the result should be
[[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
What I started off doing was creating a whole list containing all of the numbers and then split it. However I can't use the split function since its a string and don't know any proper ways to splice it properly.
Here is a function that finds your desired outcome using a double-loop.
def get_contiguous_sublists(lst):
out = [[]]
# find the length of the input list (added 1 for convenience which will be useful later)
len_lst = len(lst) + 1
# for each integer between 1 and the full length of the input list,
# we slice the input list `lst` to create new lists of this length
# and add it to the output list `out`
for length in range(1, len_lst):
# here, we are changing the starting point of the list slicing,
# i.e. whether we want to start from 1 or 2 or 3 for [1,2,3]
for i in range(len_lst - length):
out += [lst[i : i + length]]
return out
Output:
>>> get_contiguous_sublists([1,2,3])
[[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
>>> get_contiguous_sublists([1,2,3,4])
[[], [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4], [1, 2, 3, 4]]