0

after much googling i now ask. Is there a way to append an integer to the end of a variable name. Essentially creating a new variable with each iteration of a for loop. IE:

def parser(lst):
    count = 0
    for obj in lst:
        if isinstance(obj,list):
            parser(obj)
        else:
            for string in obj:
                var+count = o

This is what i get when i try to run above code:

SyntaxError: can't assign to operator
6
  • In order to help you fix the problem, please show us valid piece code to reproduce the problem and explain clearly what exactly you are trying to do. Commented Jan 6, 2014 at 4:14
  • This is a duplicate of a large number of questions on SO, although that may not be obvious to someone who doesn't know the answer. The blog posts Keep data out of your variable names and What you don't want to dynamically create variables explain why this is a bad design, and show you how to do it on the rare occasions when it's necessary, and link to a bunch of other SO questions with useful answers. Commented Jan 6, 2014 at 6:34
  • @thefourtheye The data is just my gmail contacts in "outlook csv" form. The above code was just for experimental purposes to see if it was possible. But seeing as it is bad practce to do so, there is no point in doing it. Commented Jan 6, 2014 at 19:51
  • @abarnert I apologize for the duplicate question. I was unable to find one that answered my exact question. Thank you for the links to the blog posts. Commented Jan 6, 2014 at 20:01
  • @Matt: No need to apologize. As I said, the duplicates may not be obvious to someone who doesn't already know the answer. There are a few cases like this in Python (a lot fewer than in most other languages…) that come up over and over again because anyone who first runs into the problem can't figure out what to search for. Commented Jan 6, 2014 at 20:15

2 Answers 2

6

You almost certainly want to use a list:

def parser(lst):
    vars = []
    for obj in data: # did you mean "for obj in lst:"?
        if isinstance(obj,list):
            parser(obj)
        else:
            for string in obj:
                vars.append(o) # did you mean "vars.append(string)"?

Then, instead of, say, var5, you would use vars[5].

Sign up to request clarification or add additional context in comments.

2 Comments

+1 but missing SSCCE. cving...
@DoorknobofSnow Thank you. Also You were correct in you assumption, 'data' was supposed to be 'lst'. 'Data' was the name of the ar holding the cleaned up "data". Thanks for catching that, Post edited.
1

Doorknob of Snow's answer is correct, but for completeness, you can create a new variable using locals()[var + str(count)] = o. But this is a bad idea, so don't.

1 Comment

Thank you also. This is def helpful. Advice taken.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.