Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
easy name problem
#1
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
Larz60+ write Jun-16-2021, 03:13 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Reply
#2
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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code problem - probably easy fix? colin_dent 5 831 Jun-30-2023, 01:55 PM
Last Post: deanhystad
  Problem with very easy code. janekk9002 1 1,762 Dec-10-2020, 12:57 PM
Last Post: buran
  How to start with this easy problem? Fran 8 4,074 Sep-11-2018, 09:04 AM
Last Post: Fran
  probably a easy problem for you krheigh 4 4,617 May-12-2017, 06:45 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020