-1

Ok so Basically I have this list. pets = ["mypets","herpets","hispets"]

and as this list was generated from reading the lines of a text file

textfile = open("pets", 'r')
lines = textfile.read()
words = lines.splitlines()
print(words)

I am now trying to find a way to convert this list from a list of strings into a list of variable names

pets = [mypets,herpets,hispets]

I would also like to point out that my issue is not in how to construct a list of variables as there may of been a missunderstanding.

jessyjack
  • 35
  • 4
  • 5
    Why don't you save those `mypets` lists as dictionary? – Ynjxsjmh May 14 '22 at 20:14
  • 1
    the 3 pets, mypets, herpets and hispets are imported from an external text file – jessyjack May 14 '22 at 20:17
  • I answered you. If it is suitable to save arrays with the animals themselves in the 'pets' list. Or do I need to have strings in 'pets'? – inquirer May 14 '22 at 20:20
  • 1
    Is the idea of accessing variables from their names in `["mypets","herpets","hispets"]` your own, or a requirement for some school assignment? In practice this is considered a _bad idea™_ , so if this is within your control, you'd be best to avoid it. See [How do I create variable variables?](https://stackoverflow.com/q/1373164/11082165) for more on why – Brian61354270 May 14 '22 at 20:22
  • 1
    @Brian its kind of out of my control, as the variable names for the list pets, is imported from a text file – jessyjack May 14 '22 at 20:23
  • 2
    This sounds like an [XY problem](https://stackoverflow.com/q/1373164/11082165). You don't need to create a list of variable names. What you do need is to associate some strings (mypets, herpets, hispets) with some lists of strings that you read from text files. That kind of associated mapping is exactly what dictionaries are for. – Brian61354270 May 14 '22 at 20:30

2 Answers2

1

Much better to use a dictionary as @Ynjxsjmh suggested:

all_pets = {
    'mypets': ['cat','dog','snake'],
    'herpets': ['bird','hamster','rabbit'],
    'hispets': ['fox','bees','worms'],
}
owners = ["mypets","herpets","hispets"]

for owner in owners:
    print(all_pets[owner])
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0
pets = [mypets, herpets, hispets]
print(pets[0][0])

Output

cat
inquirer
  • 4,286
  • 2
  • 9
  • 16
  • i'm looking to convert pets=["mypets","herpets","hispets"] into pets=[mypets,herpets,hispets] as I am first stuck with strings – jessyjack May 14 '22 at 20:21