Print a space separated list in Python I am trying to solve the common &quot;print a character after every item in a list, except the last one&quot; problem.
I do not want to use list indexes. There are a couple of simple ways to do this in Python, but I am not sure how to apply them to my code.
Is there a more readable/couple liner way to do this?
def echo(*args):
    for data in args:
        if data is args[-1]:
            ender = ''
        else:
            ender = ' '

        if isinstance(data, six.string_types) \
                    or isinstance(data, six.integer_types):

            print_(data, end=ender)
        else:
            op = getattr(data, '__str__', None)
            if op:
                print_(data.__str__(), end=ender)
            else:
                LOG.error(&quot;echo called with an unsupported data type&quot;)
    print_('')

Note: Code works in both Python 2 and Python 3.
I might be misreading your code, but it looks like all you want is:

def echo(*args):
    six.print_(*args, sep=" ", end="")


For something a bit more manual:

def echo(*args):
    six.print_(" ".join(map(str, args)), end="")




In terms of reviewing your actual code, on top of the issues Morwenn raises, note that:

op = getattr(data, '__str__', None)
if op:


simplifies to:

if hasattr(data, '__str__'):


However, it is rare to call magic methods directly in Python; normally you'd just do str(data) and let Python call __str__. This is safer, as although an old-style class may not implement __str__, you can still get e.g. '&lt;foo.bar object at 0x...&gt;' via str(...). 



I would include the filtering as a separate function:

def valid(arg):
    """Include a docstring to explain your filtering rules."""
    if (isinstance(data, (six.string_types, six.integer_types)) or
        hasattr(data, '__str__')):
        return True
    LOG.error("echo called with an unsupported data type")
    return False


Then echo can use filter:

def echo(*args):
    six.print_(*filter(valid, args), sep=" ", end="")