Prepending a string to alternate elements in a Python tuple So I have this piece of Python code that essentially takes a tuple, then modifies the second (and every other) element by prepending a string to it.  Unfortunately the only way I can think to do it is convert it to a list (as tuples are immutable), step through, edit and then convert back to a tuple.

It works so I can't put it on SO but it's ugly and I'm sure there's a more Pythonic way to do this using slices or something.

def prependPackageToEnpoints(urls, packageName):
    """Take web.py formatted url/endpoint tuples and prepend 
    a packageName to each of the endpoints, e.g.
    ('/Test/(.*)', 'test') becomes ('/Test/(.*)', 'Test.test')"""
    lst = list(urls)
    for i in xrange(1, len(lst), 2):
        lst[i] = packageName + "." + lst[i]
    t = tuple(lst)

    return t


I don't get to decide what the structure is, I'm using web.py and the structure it uses is a tuple.

What's the prettiest, and perhaps the most efficient way to do something like this in Python?
There may be other ways to do it, but none that I can think of that stands out as being better than what you wrote.  You could tighten up the code by adhering to PEP 8 naming conventions (use lower_case_with_underscores) and eliminating the variable t.

All I can offer is my condolences for being stuck with this stupid interface.  Note that the first thing that webpy does, as you might expect, is split up the tuple into pairs, using their own utils.group() function.


class application:
    def __init__(self, mapping=(), fvars={}, autoreload=None):
        if autoreload is None:
            autoreload = web.config.get('debug', False)
        self.init_mapping(mapping)
        …

 def init_mapping(self, mapping):
    self.mapping = list(utils.group(mapping, 2))