Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python Functional Workhorses Map

Slice syntax seems like the only good way to solve.

I tried so many other ways and these are my 2 solutions. Are there any others are in between the complexity of these? I do not think checking the instance type is really ideal, but maybe it is because its necessary in this case. Was thinking maybe a try... catch instead but didn't attempt

def reverse(item):
    item = copy(item)
    if isinstance(item, str):  
        reversed_lst = list(reversed(item))
        return ''.join(reversed_lst)
    elif isinstance(item, list):
        return list(reversed(item))
    else:
        print(f'{item} is not a string or list')
        return item

Using slice syntax

def reverse(itr):
    item = copy(itr)
    return item[::-1]

Also, the first solution above was not accepted as correct even though it does work.

2 Answers

Steven Parker
Steven Parker
217,519 Points

The first solution only works with strings and lists, so it's likely not being accepted because there are several other possible types of iterables.

The second solution is perhaps the ideal approach, as it will work with any kind of iterable without concern for type. But you don't need to bother making a copy since the slice does that for you:

def reverse(item):
    return item[::-1]
Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,029 Points

Hey Ryan Valentine, It looks like the first solution has a NameError: name 'copy' is not defined.

If you add from copy import copy, the code will pass Task 1.

Steven Parker
Steven Parker
217,519 Points

It might pass, but it still wouldn't meet the objectives.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,029 Points

If the objective is create a function that can be used with map in Task 2, then this function works there as well 🤷‍♂️