Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compressing list[0], list[1], list[2],... into a simple statement

Tags:

python

list

I have a few situations where i am taking a list of raw data and am passing it into a class. At present it looks something like this:

x = Classname(
    listname[0],
    listname[1],
    listname[2],
    listname[3],
    listname[4],
    listname[5],
    listname[6],
    listname[7],
    ...

)

and so on. This is quite long and frustrating to read, especially when i am doing it multiple times in the same file, so i was wondering if there was a simpler way to write this? Something to the effect of:

x = Classname(
    # item for item in list
)

Any help would be appreciated, my brain is fried. Cheers.

like image 678
Parakiwi Avatar asked Jun 08 '20 20:06

Parakiwi


2 Answers

Unpack the list with the *args notation.

x = Classname(*listname)
like image 153
timgeb Avatar answered Nov 15 '22 05:11

timgeb


You could use

listname = [1, 2, 3, 4, 5]

class Classname:
    def __init__(self, *args):
        print(args)

x = Classname(*listname)
like image 36
Jan Avatar answered Nov 15 '22 05:11

Jan