AF2k15 AF2k15 - 10 months ago 43
Python Question

How to create new lists with iterator as list name?

I'm using Python 2.7, and I am trying to develop a function which has the capability of reading a csv file and creating an empty list for each column. In other words, use an index iterator to concatenate 'col' with the iterator, thus creating a unique empty list for each column, e.g. empty lists named col1, col2, col3, col4, etc. My problem:

SyntaxError: can't assign to function call

from the last line in:

my_file = open( r'{}'.format( file_path ) )

for i, line in enumerate( my_file ):
if i >= 1:
row = line.split( ',' )

col_N = len( line.split( ',' ) )

for i in range( 0, col_N ):
j = i + 1
'col{}'.format( j ) = []

Answer Source


'col{}'.format( j )

is a string. Not a variable. You can't assign it a value.

To add your dinamic variable to the globals:

globals()['col{}'.format(j)] = []

Then use it regularly with name supplied by you, or as globals()['col{}'.format(j)] if j is dinamic.