Skip to content Skip to sidebar Skip to footer

Create Empty List Names Using A Loop

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 t

Solution 1:

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.

Post a Comment for "Create Empty List Names Using A Loop"