1

I am working on a simple code and I want to automate the list element accessing process in python and store them in another variable. Here is my code:

>>>names = ['James', 'Tom', 'Mark', 'Tim']
>>>def name_create():
...    number = len(names)
...    for index in range(number):
...        print("name"+str(index))
...
>>>name_create()
>>>name0
   name1
   name2
   name3

Now I want to access all names automatically one by one and store them in the above output names. Like when I do print(name0), it'll show me the name stored inside it.

Example : >>>name0
          >>>'James'
          >>>name1
          >>>'Tom'

How can I do this in python?

2 Answers2

0

In python you can't create runtime variables, but you can create a dictionary which is a variable containing other variables in key value pairs such as an index and name

The code:

names = ['James', 'Tom', 'Mark', 'Tim']

my_dict = {names.index(name): name for name in names}
print(my_dict[0])

Output:

James
TERMINATOR
  • 1,180
  • 1
  • 11
  • 24
  • You should not suggest an advanced construct like list comprehension when talking to a beginner. It's like explaining the area of a square using integrals and calculus – Alberto Pirillo Jul 29 '21 at 16:16
  • @AlbertoPirillo That won't be a problem. He solved my problem quite good. Thanks to TERMINATOR –  Jul 29 '21 at 16:22
  • @AlbertoPirillo it's not a list comprehension is a dictionary comprehension, hence the dictionary – TERMINATOR Jul 29 '21 at 18:46
  • and according to PEP20 AKA the Zen of python `Flat is better than nested.` and `Beautiful is better than ugly.`, so this is definitely more pythonic – TERMINATOR Jul 29 '21 at 18:51
-1

If I understood correctly, you want to create variables at runtime, but I believe a better practice is to use a data structure: a dictionary will probably fit your needs.

names = ['James', 'Tom', 'Mark', 'Tim']
dictionary = {}
number = len(names)
for index in range(number):
    # Add elements to the dictionary
    dictionary["name" + str(index)] = names[index]

Then you can access your variables by using name0, name1, ... as keys

print(dictionary["name0"])

Output

>> James