Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Print sublist of list in Python

Basically I have this list with this two sublist [ [1], [10, 20, 30], [100, 200], ]

I want to print each of them like this ?

1,

10,

100,

20,

200,

30,

1 Answer

Hi Artur,

Have to admit that I'm not sure if this is a perfect solution but it worked for me!

def printlist(li):
    i = 0
    while i < len(max(li, key=len)):
        for item in li:
            if i < len(item):
                print(item[i])
            else:
                continue
        i += 1

I believe the trickiest part is probably "len(max(l, key=len))" (it was for me, but luckily Stack Overflow came to the rescue). What this does is to make sure the function ends when i (the variable I'm using as an accumulator) reaches the length of the biggest sublist of the list. Aside from that what the code does is to go through all sublists and print the indexes in order starting at 0 (the first index). The else works as a way to prevent "index out of range" errors that would happen because not all sublists have the same length.

I hope this helps! Please do let me know if there's something you are not sure about. Again, keep in mind this is probably not a perfect solution and there should be ways to do this with less lines of code, but as a learner myself I wanted to give it a try.