-1

Is there a way to print out the values of a list embedded in a sentence without calling them individually? For example, instead of doing this:

test = ["baseball","brother","sister"]
print ("Bob went out to play {} with his {} and {}.".format(test[0], test[1], test[2])).

Is there a way to shorten it to something like:

print ("Bob went out to play {} with his {} and {}.".format(test[0:2]))
username
  • 75
  • 5

1 Answers1

1

As Paul Panzer points out in the question's comments, you can use * in front, though you'll need *test[0:3] instead of *test[0:2]:

test = ["baseball","brother","sister"]
print ("Bob went out to play {} with his {} and {}.".format(*test[0:3]))

This produces:

Bob went out to play baseball with his brother and sister.
Chai T. Rex
  • 2,972
  • 1
  • 15
  • 33
  • Thanks! Do you know why this seems to work with or without the [0:3]? – username Feb 19 '17 at 04:21
  • The `*` unpacks the values, without it you are just slicing the list so it is still just one item. You can also just do `*test` without the slice. [this](http://stackoverflow.com/a/36908/4831822) should help explain the usage of `*`. – Steven Summers Feb 19 '17 at 04:22
  • I see, thanks for the explanation! Paul also mentioned above that format overlooks excess arguments. – username Feb 19 '17 at 04:25