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

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,933 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!