Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass tuple as argument in Python?

Tags:

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?

like image 466
Eric Wilson Avatar asked Jun 10 '11 10:06

Eric Wilson


People also ask

Can you pass tuple as argument in Python?

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.

How do you pass multiple tuples as parameters in Python?

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.

Can I pass a list as argument in Python?

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.


1 Answers

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'> 
like image 62
viraptor Avatar answered Oct 26 '22 11:10

viraptor