Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way of accessing values in a tuple (python)

i have a function that returns a tuple of

x = (1, 2, 3, 4, 5, 6, 7, 8, 9)

i also have a class that requires 10 total args (including self)

i want the tuple to be able to populate the args in the class, but if i just put

y = Class(x)

it returns the error

> TypeError: __init__() takes exactly 10 arguments (2 given)

i know it would be possible to just use

y = Class(x[0], x[1], ... x[8])

but that seems awfully long winded. is there some better method of doing this?

like image 516
i am blueseph Avatar asked Aug 31 '26 20:08

i am blueseph


2 Answers

Use the asterisk to unpack argument lists

Class(*x)
like image 198
Praveen Gollakota Avatar answered Sep 02 '26 11:09

Praveen Gollakota


You need to unpack it:

>>> def foo(a, b, c, d, e, f, g, h, i, j):
...     return a
... 
>>> x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> foo(*x)
1
like image 43
senderle Avatar answered Sep 02 '26 11:09

senderle