0
list = ["PIG", "DOG", "CAT"]

Was wondering how can I iterrate through the list and assigned each item as a new variable? Ideally i would want to create these variables and initialize it inside a loop.

Expected outcome:
var1 = "PIG"
var2 = "CAT"
var3 = "DOG"
to3
  • 29
  • 5

1 Answers1

2

You can do this -

ls=["PIG", "DOG", "CAT"]
cntr=1
for i in ls:
    locals()['var'+str(cntr)] = i
    cntr += 1

You will get output as:

var1 = "PIG"
var2 = "CAT"
var3 = "DOG"
Gary
  • 909
  • 8
  • 20
  • 2
    Accessing `locals` like this is bad practice and likely to lead to buggy behaviour for the OP down the line. Use a dictionary – roganjosh Feb 10 '20 at 17:12
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the "Answer Well-Asked Questions" section, and therein the bullet point regarding questions that "have been asked and answered many times before". That's particularly important here, where the *best* answer is arguably not a literal one, but one that instructs the user to store their `PIG`, `DOG` and `CAT` values as keys in a dictionary instead. An already-answered copy of the question will already have *both* the literal answer and the best-practice one present, providing the OP with more context and choice. – Charles Duffy Feb 10 '20 at 17:13
  • @CharlesDuffy - Makes sense! – Gary Feb 10 '20 at 18:23