Python split list into several lines of code
Asked Answered
L

4

7

I have a list in Python which includes up to 50 elements. In order for me to easily add/subtract elements, I'd prefer to either code it vertically (each list element on one Python code line) or alternatively, import a separate CSV file?

list_of_elements = ['AA','BB','CC','DD','EE','FF', 'GG']

        for i in list_of_elements:
        more code...

I'd prefer code like this:

list_of_elements = 
['AA',
'BB',
'CC',
'DD',
'EE',
'FF', 
'GG']
    
        for i in list_of_elements:
        more code...

Just to clarify, it's not about printing, but about coding. I need to have a better visual overview of all the list elements inside the Python code.

Luciusluck answered 26/4, 2020 at 20:46 Comment(4)
Have you tried it? There's no reason why you can't split a list across lines like that. Your indention of the following for loop, on the other hand...Dillard
Add a trailing comma to the last element, then use an autoformatter to format your code (pyformat perhaps)Lecythus
Put backslash next to =... Or put the left bracket next to =.Supposed
Right. The rule is that, if there is an open paren, bracket, or curly brace, then you can continue the line to the next line with no additional syntax needed.Shipentine
W
12

The first line should contain the first element, like this:

list_of_elements = ['AA',
'BB',
'CC',
'DD',
'EE',
'FF', 
'GG']

or as Naufan Rusyda Faikar commented: Put backslash next to = Or put the left bracket next to =.

list_of_elements = \
['AA',
'BB',
'CC',
'DD',
'EE',
'FF', 
'GG']

list_of_elements = [
'AA',
'BB',
'CC',
'DD',
'EE',
'FF', 
'GG']

All three will work.

Wiersma answered 26/4, 2020 at 20:52 Comment(1)
Thx, it did work. The first element needs to be in the first line.Luciusluck
L
2

The best option :


list_of_elements =\
[
'AA',
'BB',
'CC',
'DD',
'EE',
'FF', 
'GG'
]
Lurleen answered 27/12, 2023 at 17:51 Comment(0)
M
1
list_of_elements = ['AA','BB','CC','DD','EE','FF', 'GG']
new_code = '[' + ',\n'.join(list_of_elements) + ']'

new_code will be like this:
[AA,
BB,
CC,
DD,
EE,
FF,
GG]

Copy and paste it.

Millner answered 26/4, 2020 at 21:1 Comment(0)
I
0

If you are on a Unix system you can run this command: sed -i 's/,/,\n/g' yourFile.py. This will add a line break at the end of every comma in your file (careful if you have commas in some other parts of your code, like strings and comments, and not just in lists).

Alternatively, if you use VS Code you can select the row with your list that you want to display more nicely and then click Ctrl+F. Then click Alt+L so you only replace commas in the selected row. Then write , in Find box and ,\n in Replace box. Click Ctrl+Alt+Enter to replace all.

Ipsambul answered 26/4, 2020 at 20:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.