1

I have an array on hand. Now I'd like to have a combined print of text and array entries, so I'd use .format.

I'd like to now if there is a way to get the following work with that for loop (not a[0],a[1],a[2]).

a = [1,2,3]
print("""
A is {}
B is {}
C is {}
""".format(i for i in a))

This one returns IndexError: tuple index out of range

0

1 Answer 1

1

Use the * to unpack the arguments as an argument list:

a = [1,2,3]
print("""
A is {}
B is {}
C is {}
""".format(*[i for i in a]))

Or even better, if you’re not dependent on the individual contents of the list;

a = [1,2,3]
print("""
A is {}
B is {}
C is {}
""".format(*a))

Python reads both of these identically: *a is unpacked as an argument list. You can do something similar with dictionaries (using a double ** which unpacks keyword arguments):

a = {"alpha": 1, "beta": 2, "gamma":3}
print("""
A is {alpha}
B is {beta}
C is {gamma}
""".format(**a))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.