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 <module> 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?
In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.
To expand tuples into arguments with Python, we can use the * operator. to unpack the tuple (1, 2, 3) with * as the arguments of add . Therefore, a is 1, b is 2, and c is 3. And res is 6.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
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() # <- missing argument type(()) # returns <type 'tuple'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With