0

Beginner's question.

I want to create several empty lists and name them. Currently I am doing it the foolproof but cumbersome way,

size_list=[]
type_list=[]
floor_list=[]

I am trying to do it less cumbersome,

for item in ['size', 'type']:
    item+'_list'=[]

however, this results in the following error,

    item+'_list'=[]
    ^
SyntaxError: can't assign to operator

Can this be fixed easily, or should I use another method to create empty lists with names?

martineau
  • 119,623
  • 25
  • 170
  • 301
LucSpan
  • 1,831
  • 6
  • 31
  • 66

1 Answers1

4

If you have lots of data to track in separate variables, don't rely on related variable names. What will your code do with all these variables after you have defined them? Use a dictionary:

datalists = dict()
for item in ['size', 'type']:
    datalists[item] = []

Addendum: By using a dictionary, you have one variable containing all list values (whatever they are) for your different labels. But perhaps (judging from your choice of names) the values in the corresponding list positions are meant to go together. E.g., perhaps size_list[0] is the size of the element with type type_list[0], etc.? In that case, a far better design would be to represent each element as a single tuple, dict or object of a custom class, and have a single list of all your objects.

Thing = namedtuple("Thing", ['size', 'type', 'floor'])
spoon = Thing(size=33, type='spoon', floor='green')

things = []
things.append(spoon)

Tuples (named or otherwise) cannot be modified, so this might not be what you need. If so, use a dictionary instead of a tuple, or write a simple class.

alexis
  • 48,685
  • 16
  • 101
  • 161
  • Yes, indeed `x_list[i]` corresponds with `y_list[i]` for any `x,y in ['size', 'type',..., 'floor'] such that x!=y` and `i=0,1,...,3000`. Every `i` represents a property ad. Ultimately I'd like to create a table with each apartment `i` on a row, and as columns `['size', 'type',..., 'floor']`. Not sure if your addendum suits this? – LucSpan Mar 14 '17 at 09:10
  • It does. Create a tuple or dictionary (or object of a custom `Apartment` class) for each apartment. Put differently: Think about how you'd represent **one** apartment, then simply make a list of them. – alexis Mar 14 '17 at 10:21
  • Thanks! I'll contemplate. – LucSpan Mar 14 '17 at 10:29