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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Adam Harms](https://secure.gravatar.com/avatar/86529816c00c239b953cf8622cc808e5?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Adam Harms
9,826 Pointstraversing nested lists, need help in python
If I have a list now can I get all of the items out of the lists? The catch is for me, that it has lists within the lists and both integers and strings in the list. Thanks
python
test = [1, 2, [0, [3, 5, 'weather'], 1], 'hats', [0, 1]]
How can you pull out so it prints like this... (1, 2, 0, 3, 5, 'weather', 1, 'hats', 0, 1)
1 Answer
![Stuart Wright](https://uploads.teamtreehouse.com/production/profile-photos/6368232/micro_footgolf.jpg)
Stuart Wright
41,119 PointsThis seems like a good use for recursion. If you've never come across recursion before, it's a really interesting subject to read up on. The important thing to know for the purposes of this problem is that we will write a function that calls itself every time it comes across a nested list inside the list it's traversing. By appending non-list items when you come across them, and extending the outer list with the inner list when you come across a list, you'll end up with the result you're after. You can try it with an even deeper nested list than the one you've given in the example and this code will still work. It's not very easy to explain in a few lines, you might be better off just reading up on the subject if it's completely new to you:
http://openbookproject.net/thinkcs/python/english3e/recursion.html
Here's my solution - line 5 is where the magic happens, as the function calls itself to get to work on the inner list.
def combine(input_list):
output_list = []
for item in input_list:
if type(item) is list:
output_list.extend(combine(item))
else:
output_list.append(item)
return output_list
combined_list = combine(test_list)
print(combined_list)