0

So I am trying to loop over a list of list names and trying to assign value to its element by index.

But the problem is within the loop, it is being referred to as a string literal instead of a list which throws up errors. Below is the snippet of the code I am dealing with.

    placeholder_list=["cat_list","cat_list"]
    for i in range(len(list_Col)):
        specific_function_output
        placeholder_list[i][int(index)]=specific_function_output

The problem comes at this step: the python is interpreting placeholder_list[i] as "cat_list", what I was expecting is

cat_list[int(index)] 

but it is actually being treated as "cat_list"[int(index)] which is genrating the generic error

TypeError: 'str' object does not support item assignment

This might have a very simple solution, but I am having a bit of a struggle to find a solution for this. And also having not too familiar with the technical terms or details about the backdrop doesn't help.

In general, for programming, how should we get the actual instance by referring back to their tokenize names by the index within a loop -- this is how I could conceptualize the problem. But again, I might be missing some technical details on it.

  • Just use a dictionary. This is super fragile anyways though and suggests you have set things up awkwardly. If you change the `cat_list` variable name at some point and forget to update all the strings, you'll end up with weird errors. There's likely a better way of doing what you're trying to do. – Carcigenicate Oct 24 '19 at 16:42
  • Loosely related to [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables). – Carcigenicate Oct 24 '19 at 16:46
  • Thank you for the input. However, for the current situation, I have stumbled across this thread [link] (https://stackoverflow.com/questions/30358269/how-to-reference-a-list-using-a-string-in-python) and in particular, the `eval()` function seems to have accomplished what I was expecting it do. – user3674508 Oct 24 '19 at 17:15
  • That's an extraordinary poor solution though. It'll be much slower than any other solution, and can lead to security issues if the string you're evaluating contains any information taken from outside of the program. Again, rethinking how you have things set up is a much better idea. Refactoring is a pain in the short term, but can save you in the long term. – Carcigenicate Oct 24 '19 at 17:17
  • `eval(placeholder_list[i])[int(index)]=specific_function_output` this is the modification I did -- and you are right for it being slow. But for this specific project, I may not advance much further than this, however as a principle, what you said about using dictionary would be my preference too. – user3674508 Oct 24 '19 at 17:38

0 Answers0