pythonprintingtuples

Output the contents of a tuple in a print statement


I would like to print the contents of a tuple with a print statement like this:

print("First value: %i, Next four values: %i %i %i %i, Next three values: %i %i %i\n" % (myTuple[0], myTuple[1], myTuple[2], myTuple[3], myTuple[4], myTuple[5], myTuple[6], myTuple[7]));

Now as you can see in the example above the elements in a tuple are going to be output in order, but the format is such that you can't easily use a loop. Is there a way to just specify the whole tuple/list/set (or a given range) in print statement without specifying each element separately, something like this?

 print("First value: %i, Next four values: %i %i %i %i, Next three values: %i %i %i\n" % (myTuple[:7));

Solution

  • If using str.format(), which you probably should be, you can use the iterable-unpacking operator *:

    myTuple = tuple(range(10))
    print("There are 7 values {} {} {} {} {} {} {}".format(*myTuple[:7]))
    # There are 7 values 0 1 2 3 4 5 6
    

    If using old-style format strings, you can just give my_tuple[:7] as the argument, since it expects a tuple or other iterable after the %:

    print("There are 7 values %i %i %i %i %i %i %i" % myTuple[:7])
    # There are 7 values 0 1 2 3 4 5 6