Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize complex nested lists in Python in many lines?

Python requires indenting. So, how to initialize complex nested objects inline?

Should I write them in one long line

rewards = [[-0.04, -0.04, -0.04, -0.04], [-0.04, 0, -0.04, -0.04], [-0.04, -0.04, -0.04,-0.04]]

Or can I wrap them somehow?

UPDATE

My question is not about breaking long lines, which is clearly written in documentation, but about breaking long lines in case of defining complex nested structures, like list of lists of dictionaries of lists. I was unable to beleive we should use line continutaion syntax here.

UPDATE 1

No it's not a duplicate.

like image 808
Dims Avatar asked Sep 01 '25 03:09

Dims


2 Answers

One way is to use:

rewards = [
    [-0.04, -0.04, -0.04, -0.04],
    [-0.04, 0, -0.04, -0.04],
    [-0.04, -0.04, -0.04,-0.04]
]

Note that any whitespace within a list for separating elements is redundant, as the lexer will remove it; so this is simply a matter of readability as per one's taste.

You could write it in one line, however, you will very easily hit the 80 char limit when doing so with long nested lists, and I personally don't find that representation reader friendly.

like image 168
Anshul Goyal Avatar answered Sep 02 '25 16:09

Anshul Goyal


Inside parenthesis, including [, {, and (, you can use any formatting you want.

like image 23
thebjorn Avatar answered Sep 02 '25 16:09

thebjorn