-1

I want to print all elements of all sublists which I am able to do with the following loop

sublists=[[1, 2, 3], [4, 5, 6], [7, 7, 7]]
for i in sublists:
    for j in i:
        print(j)

but if I use this function, it only prints the first item of the first sublist. Why is that? How do I make this function work ?

def sl_check(sl):
    for i in sl:
        for j in i:
            return j
print(sl_check(sublists))

1 Answers1

0

The return breaks out of the loop, so you'll need to collect all the elements in a new list and then return everything outside the loop:

def sl_check(sl):
    all_elements = []
    for i in sl:
        for j in i:
            all_elements.append(j)
    return all_elements

sublists=[[1, 2, 3], [4, 5, 6], [7, 7, 7]]
print(sl_check(sublists))

PangolinPaws
  • 670
  • 4
  • 10