3

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.

Dims
  • 47,675
  • 117
  • 331
  • 600

3 Answers3

9

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.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
3

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

thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

You may wrap any line in Python with a trailing backslash:

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

Still it's not really needed here, as it's mentioned in the previous answer

AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27
  • 5
    This is a place where you don't need (and really shouldn't) use a line-continuation character. – thebjorn Jan 23 '17 at 13:26
  • 1
    No, it really isn't :-) You can remove it without effecting the semantics -- and if you want it more readable you should do what @mu did and provide proper semantic formatting ;-) – thebjorn Jan 23 '17 at 13:33