How to loop through a list of variables which are not defined in the current scope

Currently I am looking at the lesson: Referring to Member Variables in the section on classes:

https://www.codecademy.com/courses/learn-python/lessons/classes/exercises/referring-to-member-variables?action=resume_content_item

While not necessary here (since there is only a small number of items to type), I would like to know how to loop through the list of characteristics for my instances of the Car() class. My attempts have been along the lines of the following (I’ve also done it without the quotes, but thought it may work if the words were strings):

for x in ["model", "color", "mpg"]:
  print(my_car.x)

I have used Stata extensively, and this would be a simple thing in Stata, looking something like:

local loop_list model car mpg
foreach x in `loop_list' {
  display my_car.`x'
}

There seem to be two issues in python when trying to do this. First, if I do not make them strings, the items in the list return an undeclared variables error (in stata, this is not an issue for local lists). The second is that within the line print(my_car.x), I have not been able to tell python that the .x is referring to the item I am looping through (in stata, this is done with the `’).

Is constructing this sort of thing possible in python? It seems like the second issue would be most important to deal with, as I may want to loop through a number of items and save the differences as different files, related to which item I am looping through.

Thanks!

1 Like

From your description I get the feeling that Stata’s objects aren’t quite the same as Python ones.
Maybe all you’re after is a hash table.
If a python object has two attributes, then they are probably different in some way and you would therefore not iterate over them. If they are of different kinds, can’t really… apply the same operation on them.

What python doesn’t have is macros/templates, or symbols/variables as values. Strings can be used to this effect but I doubt it matches your intentions.

You’ve given a solution to the problem, but I’m not sure what the problem is.

If all you want is to display them, then I’d argue your loop isn’t helping you. You’re still writing out the name of each one, so you may as well do the same thing without the loop:

from __future__ import print_function  # I refuse to use the old print statement

print(
    thing.x,
    thing.y,
    thing.z,
)
2 Likes

The quickest example of this is if I am running several regressions over a list of variables, and then wish to save the output as a file with that variable in the filename.

However, these actions are beyond what I know how to do in python thus far, so the answer may become clear as a I move forward. I’ll look into some of the things you mentioned (ex: hash table), and move forward in python so that either I can answer my own question, or I can ask it in a more intelligible way.

Thanks!

1 Like

More of a table/spreadsheet than some plain object then.

Objects define their own behaviour, things like operators and whether they’re iterable, callable, indexable, attributes and so on.

So you’d have an iterable object which also expose the columns as attributes. This is pretty easy to make, but you’d probably want a bunch of other operations too, so, you’d look for a module to do it for you:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
...                   columns=['a', 'b', 'c', 'd', 'e'])
>>> df
   a  b  c  d  e
0  4  8  4  6  2
1  5  1  9  6  8
2  8  4  8  0  4
3  4  7  4  0  3
4  1  9  1  8  2
>>> df.c
0    4
1    9
2    8
3    4
4    1
Name: c, dtype: int64
>>> df['e']
0    2
1    8
2    4
3    3
4    2
Name: e, dtype: int64
>>> df.columns
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
1 Like