How to generate all subarray or list in the given list or array using python

0
3 min read

A different form of this Problem Statement

  • print all sublists in list
  • print all subarray in array using python
  • find all subarrays of an array

User: Oh wait but what does subarray really mean, Can you please elaborate it using some example?

Okay, So let start explanation using some example.

Input : List = [1, 2, 3]
Output : [[], [1], [2], [3], [1, 2], [2, 3], [1,2,3]]

Input : List = [1, 2, 3, 4]
Output : [[], [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4], [1, 2, 3, 4]]

User: Wait, Sorry to say, but you have forgotten to mention [1, 3] in the first example.

Thanks to mention this, But it is not wrong example, [1, 3] will definetly get a place, when we are finding out the permutation and combination of list to generate a pair. But Here we are generating just sublist of list. Both case are different.

User: Okay,Now I have better understanding. So Now what will be the approach to solve this condition.

Okay, Let’s move on the approach of this statement.

Approach will be that we are going to run two nested loop till the length of the given list. The outer loop will pick up starting element and inner loop will considers all elements on right of the picked elements as ending element of subarray. To do this thing, slicing would be better to get subarray.

To make it more simple, Here is the Five step process to approach this statement.

Step 1: Run a loop till the end of the given list.

Step 2: Iterate over a loop from i+1 to end(length) of the list to get all the sublists from i to its right.

Step 3: Slice the sublists from i to j

Step 4: Append it to another list to store it.

Step 5: Now, print the list at the end(Not necessary just to see the result)

User : It looks cool can you please provide me code for this approach.

Why not, Let write code for this approach using python.

"""
 function to generate all the sub lists 
"""
def generate_sub_lists(arr): 
  
    # store all the sublists  
    sub_list = [[]] 
      
    # first loop  
    for i in range(len(arr) + 1): 
          
        # second loop  
        for j in range(i + 1, len(arr) + 1): 
              
            # slice the sublist
            sub = arr[i:j] 
            sub_list.append(sub) 
      
    return sub_list 
  
arr = [1, 2, 3] 
print(generate_sub_lists(arr)) 

# Code published on Freshlybuilt.com

Output

[[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]

This is the output of the program, that is generated using the above code.

If you liked this article, Please create an account on this platform to support our community. This community is completely run by students.

Youtube Video For Reference

Tags:
Choose your Reaction!
Leave a Comment