0

I have a list of strings. I now want to create a list for each string within my original list. I don't want to hard code in the new lists.

For example if my list is my_list = ['Paul', 'Ringo', 'John', 'George'] I want to create 4 new lists, one for each string (Paul = [ ] Ringo = [ ] etc). Any ideas? Thanks!

codian
  • 19
  • 4
  • Create a dictionary whose keys are the band members' names and whose corresponding values are the lists of attributes associated with each band member. – jarmod Feb 04 '21 at 23:35
  • You can use exec updated the answer – PDHide Feb 04 '21 at 23:49
  • @codian I know it's been a while, but please, let us know if any of answers below have what you needed. If so, please accept the one you prefer to "close the question". Hope it has helped! – rodrigocfaria Dec 28 '21 at 02:14

3 Answers3

1

You cannot dynamically name variables on run time with Python. However, you could fill a dictionary where the keys are the items from the list and the values are an empty list. Like this:

my_list = ['Paul', 'Ringo', 'John', 'George']
my_dict = {}

for name in my_list:
    my_dict[name] = []

print(my_dict)
# {'Paul': [], 'Ringo': [], 'John': [], 'George': []}

For bonus, you can use dictionary comprehension which is way shorter. Like this:

my_list = ['Paul', 'Ringo', 'John', 'George']
my_dict = {item:[] for item in my_list}

print(my_dict)
# {'Paul': [], 'Ringo': [], 'John': [], 'George': []}

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
1

This is a case to use a dictionary:

my_list = ['Paul', 'Ringo', 'John', 'George']

dict = {}

for beatles in my_list:
    dict[beatles] = []

print(dict)

dict['Paul'].append('Yellow Submarine')

print(dict['Paul'])
rodrigocfaria
  • 440
  • 4
  • 11
0
   my_list = ['Paul', 'Ringo', 'John', 'George']

   b=[ (i+'=[]') for i in my_list]
   for i in b:
        exec(i)
   print(Paul)

Use execute function to execute string statement as python statements

Above lines creates four list variables

PDHide
  • 18,113
  • 2
  • 31
  • 46
  • There are some things that you can do, but probably shouldn't. – jarmod Feb 05 '21 at 02:03
  • @jarmod could you mention why not ? – PDHide Feb 05 '21 at 13:48
  • Unless you absolutely need this type of function, which is not the case here, it’s typically best to avoid any possibility of executing arbitrary and potentially untrusted code. Also, see https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided. Let’s say at some point in the future the code changes from a static list of Beatles’ names to a list that’s populated from user input - a devious user can now enter malicious Python code, instead of a person’s name, and your program will execute it. – jarmod Feb 05 '21 at 13:53
  • @jarmod yes i added the code because its a static code and also the user mention to create list not dictionary of list – PDHide Feb 05 '21 at 14:04