What is the logic of python * syntax when iterating over a tuple sequence?
The
code is taken from page 4 of the third edition of pythoncookbook. The code is as follows:
records =[
("foo", 1, 2),
("batr", "hello"),
("foo", 3 ,4),
]
def do_foo(x,y):
print("foo", x ,y)
def do_bar(s):
print("bar", s)
for tag, *args in records:
if tag == "foo":
do_foo(*args)
elif tag == "bar":
do_bar(*args)
:
foo 1 2
foo 3 4
the principle of the code is not very clear. Please explain it. Thank you.
I guess your confusion may be why the: bar hello results didn't show up?
because the second item of your records is misspelled: ('batr',' hello') should be ('bar',' hello'),
In [1]: records =[
...: ('foo', 1, 2),
...: ('bar', 'hello'),
...: ('foo', 3 ,4),
...: ]
...: def do_foo(x,y):
...: print('foo', x ,y)
...:
...: def do_bar(s):
...: print('bar', s)
...:
...: for tag, *args in records:
...: if tag == 'foo':
...: do_foo(*args)
...: elif tag == 'bar':
...: do_bar(*args)
...:
foo 1 2
bar hello
foo 3 4
the simple explanation is:
* arg decomposes several elements after tag.
for example, the three elements in the list record are: ('foo', 1 hello' 2) (' bar', 'hello') (' foo', 3, 4)
tag is' element after foo', (1 br 2) is * args, so print foo 1 2
tag as' element behind bar', 'hello' is * args, So print bar hello
tag as' foo', followed by the element (3) is * args, so print foo 3 4
< H2 > use * to process the remaining elements < / H2 >
-- page 25 of "smooth python"
in Python, it is a classic way for a function to use * args to get an uncertain number of parameters.
in Python 3, this concept extends to parallel assignments:
>>> a, *body, c, d = range(5)
>>> a, body, c, d
(0, [1, 2], 3, 4]
>>> *head, b, c, d = range(5)
([0, 1], 2, 3, 4]