1

How do I pop character from a certain list and make it my variable name? For example:

list1=['a','b','h','j']

In this case, how do I remove 'a','b','h','j' from the list and make it a variable?

a=input("Enter a name")
b=input("Enter a name")
h=input("Enter a name")
j=input("Enter a name")

I have dynamically created the list in my project where the contents of the list are appended from some other action.

Hrishikesh D Kakkad
  • 173
  • 1
  • 1
  • 12
  • `variable = list1.pop()` with an optional index as argument. – Klaus D. Feb 02 '19 at 05:27
  • *"...make it a variable?"* You shouldn't create variables like that. If you are trying to read from user and put all inputs to list, this is not the way. – Austin Feb 02 '19 at 05:34
  • You don't. Use a list to store inputs and adress them by index or you use a dictionary for key:value pairs if it makes sense - I can see no place where your example code would warrant using a dictionary. – Patrick Artner Feb 02 '19 at 05:42

1 Answers1

0

Depending on if you want these variables as local or global. For global you can use:

while list1:
    variable = list1.pop()
    globals()[variable]=input(“Enter a name”)

For local, just replace globals() with locals()


Or you can go with a dictionary. Pop the items from list to be keys and assign value to those keys.

Tim
  • 2,557
  • 1
  • 10
  • 23