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

Herman Brummer
Herman Brummer
6,414 Points

How can I refactor this?

def combo(input1, input2):
    counter = 0
    new_list = []

    for item in input1:
        x = item, str(input2[counter])
        new_list.append(x)
        counter = counter + 1

    return new_list        

print (combo("abc", "def"))

I got this done after much work and faffing out, but yikes its long.

1 Answer

Chris Jones
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,921 Points

Hey Herman,

I think your code looks good and isn't in need of much refactoring, but if you just want to know someone else's opinion - here's what I would change:

def combo(input1, input2):
    counter = 0
    new_list = []

    for item in input1:
        new_tuple = (item, input2[counter])
        new_list.append(new_tuple)
        counter += 1

    return new_list        

print (combo("abc", "def"))

The x variable wasn't obviously a tuple to me (although I haven't done much python for a while), so renaming that variable to new_tuple will help someone looking at your code understand it faster. Also, I enclosed the new_tuple variable instantiation in parenthesis just because that seems to be the common practice after I googled it briefly. Next, you can increase the counter variable using the shorthand operator += 1 instead of counter + 1. Lastly, you don't need to use the str function because you're passing a string already for the input2 parameter.

Overall though, I thought you did well :). Let me know if you have any more questions. Keep it up!