Python Forum
Variable in for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Variable in for loop (/thread-28151.html)



Variable in for loop - samuelbachorik - Jul-07-2020

Hello guys i have simple code like this. Please can someone give me example how to update this code to make for every name in list new variable ? I just want this for loop to make 3 variables with 3 names from list. Name1 = samuel, name2 = max, name3 = john

Thank you

names = ["samuel","max","john"]

counter = 0

for i in names:
    name1 = names[counter]
    counter +=1


print(name1)



RE: Variable in for loop - GOTO10 - Jul-07-2020

The short answer is that there is no usage case that justifies doing this. You are much better off referencing your existing list, or you could use a dictionary if that suits your purposes better. Creating dynamically named variables adds unnecessary complexity to your code and makes maintaining it much more difficult.

With that said, it is technically possible to do what you are asking with the exec() function. Again, this is NOT recommended:
names = ["samuel","max","john"]
 
for i, n in enumerate(names):
    exec('name' + str(i + 1) + '= n')
 
print(f'name1 = {name1}, name2 = {name2}, name3 = {name3}')
Output:
name1 = samuel, name2 = max, name3 = john



RE: Variable in for loop - hussainmujtaba - Jul-21-2020

I actually get you are tring to do here, but its not possible to do so but alternatively you can use dictionary to do somewhat same.Here is the code
names = ["samuel","max","john"]
dic_names={}
for i,j in zip(names,range(len(names))):
    index="name{}".format(j)
    dic_names[index]=i
print(dic_names)
Output:
{'name0': 'samuel', 'name2': 'john', 'name1': 'max'}
Also you can access each of them by using dictionary. Here is a basic guide to understand dictionaries


RE: Variable in for loop - buran - Jul-21-2020

creating names dynamically is something you don't want to do.
use proper data structure
keys = [f'name{i}' for i in range(3)]
values = ["samuel","max","john"]
names = dict(zip(keys, values))
print(names)



RE: Variable in for loop - ndc85430 - Jul-21-2020

But if you're really just going to call your keys namei where i = 0, 1, 2, ..., n, why bother with a dictionary? It sounds like you just want a sequence (i.e. a list or tuple).