i am a beginner and i want output to print in separate sub-lists in the main list only once

Minor changes to your code and it works perfectly.

The changes I made to your code.

#Extra lists used inside for loop for storing data
l_extra = [ ]

These two lines, I moved them inside the for loop for i in range(0, n):. Why? You need to reset the list every time. Otherwise, all your values will get added into the list. Your final list will look a bit wacky.

The second change is to remove the [ ] bracket from ele = [input()] Instead, I made it ele = input() That way it just accepts the input values and appends to your l_extra list

To help you figure out which list you are entering the value, I changed your input statement a bit. It has been updated to

list1 = int(input("Enter number of elements in List " + str(i+1) + " : "))

Below is the working code.

def Sublist_counter(l):
    count = 0
    for c in l:
        if type(c) == list:
            count+=1
    return count


#Main List for storing sublists
l_main = [ ] 

n = int(input("Enter number of Lists : ")) 
  
for i in range(0, n):
    #Extra lists used inside for loop for storing data
    l_extra = [ ]
    
    list1 = int(input("Enter number of elements in List " + str(i+1) + " : ")) 
    for j in range(0,list1):
        ele = input()       
        l_extra.append(ele)
    l_main.append(l_extra)
         

print("...You have entered the following Lists with data inside the main List...")
print(f" {l_main}" )
print(f"Number of Sublists are :{Sublist_counter(l_main)}")

The output of the above code is:

Enter number of Lists : 3
Enter number of elements in List 1 : 4
Apple
Banana
Salt
Peach
Enter number of elements in List 2 : 3
Morning
Afternoon
Evening
Enter number of elements in List 3 : 5
Monday
Tuesday
Wednesday
Thursday
Friday
...You have entered the following Lists with data inside the main List...
 [['Apple', 'Banana', 'Salt', 'Peach'], ['Morning', 'Afternoon', 'Evening'], ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']]
Number of Sublists are :3

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top