0

I want to split python code over two lines, my code is something similar to:

if long_named_three_d_array[first_dimension][second_dimension][third_dimension] == somevalue:
    //dosomething

I want to split above if condition over two lines.

Please help. Thanks.

hrishikeshp19
  • 8,838
  • 26
  • 78
  • 141

3 Answers3

5

In Python, the LHS can be bracketed.

>>> a = {}
>>> a[1] = {}
>>> a[1][2] = {}
>>> (a[1][2]
... [3]) = ''
>>> a
{1: {2: {3: ''}}}
>>> (b) = 2
>>> b
2

This means you can write your line as

if (long_named_three_d_array[first_dimension] 
    [second_dimension]
    [third_dimension] ) == somevalue:
# Rest of code here, obviously properly indented in for the if.
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

You can use the line break continuation character, \.

if long_named_three_d_array[first_dimension] \
    [second_dimension]\
    [third_dimension] == somevalue:
# Rest of code here, obviously properly indented in for the if.
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • thanks, I am looking for somehting similar, but it is not working for me. Can you confirm again. – hrishikeshp19 Apr 10 '12 at 02:33
  • 2
    @hrishikeshp19 Make sure you don't have any trailing whitespace after the \ character. – Michael Anderson Apr 10 '12 at 02:34
  • 3
    The "trailing slash" line continuation is evil because 1) any whitespace after the slash will break it, as @MichaelAnderson has noted, and also 2) any **comments** after the slash will break it. This is why Python Style Guide, PEP 8, recommends that you don't use the backslash syntax for line continuation. – Li-aung Yip Apr 10 '12 at 02:54
  • The if expression can be put into brackets instead. Bracketed expressions can be broken into multiple lines without the use of backslashes. – yak Apr 10 '12 at 07:12
  • @yak: I agree with you and Li-aung Yip. The backslash *is* another way to do it, but bracketing the LHS is the preferred way. – Makoto Apr 10 '12 at 07:22
1

One approach would be to use a temporary variable:

tmp = long_named_three_d_array[first_dimension][second_dimension][third_dimension] 
if tmp == somevalue:
    //dosomething

though shorter, yet descriptive variable identifiers would be a better choice if that's possible.

Levon
  • 138,105
  • 33
  • 200
  • 191