Suppose I want a list of tuples. Here's my first idea:
li = []
li.append(3, 'three')
Which results in:
Traceback (most recent call last):
File "./foo.py", line 12, in
li.append('three', 3)
TypeError: append() takes exactly one argument (2 given)
So I resort to:
li = []
item = 3, 'three'
li.append(item)
which works, but seems overly verbose. Is there a better way?
解决方案
Add more parentheses:
li.append((3, 'three'))
Parentheses with a comma create a tuple, unless it's a list of arguments.
That means:
() # this is a 0-length tuple
(1,) # this is a tuple containing "1"
1, # this is a tuple containing "1"
(1) # this is number one - it's exactly the same as:
1 # also number one
(1,2) # tuple with 2 elements
1,2 # tuple with 2 elements
A similar effect happens with 0-length tuple:
type() #
type(()) # returns