views:

221

answers:

2

I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string format method. As a toy example, let us define

thelist = ['a', 'b', 'c']

I would like to do a print statement like print '{0} {2}'.format(thelist) and print '{1} {2}'.format(thelist)

When I run this, I receive the message IndexError: tuple index out of range; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate thelist to 'a', 'b', 'c'.

I tried using a tuple and received the same error.

What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful.

My actual use is much longer and more tedious than the toy example.

+2  A: 
'{0} {2}'.format(*thelist)

docs

SilentGhost
irrefragable answer
Rorick
+8  A: 

.format(*thelist)

It's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the tutorial.

It doesn't just work on lists, though, it works for any iterable object.

Devin Jeanpierre
+1: Quote the documentation.
S.Lott
I knew you'd like that. :)
Devin Jeanpierre
I think it's referred to as "unpacking".
regan
@Devin: There is much similarity between binding some names via `=` operator and binding function parameters names on function call.
J.F. Sebastian
You are correct. Which also means I linked to the wrong section (off by one). Corrected.
Devin Jeanpierre
@J.F. Sebastian: They're diverging significantly. Many of the similarities are being dropped-- for instance, in 3.0, one cannot def f((a, b), c). One can still do (a, b), c = [(1,2), 3] .
Devin Jeanpierre
@Devin: you haven't followed your own link? just in a next section comment says "call with arguments unpacked from a list".
SilentGhost
@SilentGhost: Yes. I didn't read titles, I just looked for "*args".
Devin Jeanpierre