Python Forum

Full Version: easy name problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am a beginner in Phyton. It is a very basic question I guess, but pls help me anyway :)

listA=[]
a=input()
globals()[a]=[]    #generates a new list with the name of the input string
listA.append(????????)    #question
--> I would like to add the new list to listA. I know the name is in a, but if I put a in, the string gets added to listA and not the new list.
What do I have to put inside the brackets?

Cheers
You should not use globals() that's the internal dictionary that Python use.
Can make visible dictionary that do the same,then it's much more understandable and readable for all.
Here a look a two versions.
list_a = []
animal = input('Enter a animal: ') # cat
more_animals = ['Sheep', 'dog']
list_a.append(animal)
list_a.append(more_animals)
print(list_a)
Output:
['cat', ['Sheep', 'dog']]
So this is normal way to make a list and append to it,will lose refence to variable names.
If need also names for what is the data structure then can use a dictionary.
list_a = []
animal_dict = {}
animal_dict['animal'] = input('Enter a animal: ')
more_animals = ['Sheep', 'dog']
animal_dict['more_animals'] = ['Sheep', 'dog']
# Can also append a dicionray to a list
list_a.append(animal_dict)
print(animal_dict)
print(list_a)  
Output:
{'animal': 'cat', 'more_animals': ['Sheep', 'dog']} [{'animal': 'cat', 'more_animals': ['Sheep', 'dog']}]
So now we have a visible dictionary that really dos the same as globals().
If first code i could to this which is a bad💀 way of doing this.
>>> globals()['more_animals']
['Sheep', 'dog']
In second code it make more sense as can do this.
>>> animal_dict['more_animals']
['Sheep', 'dog']