Jul-07-2020, 11:33 AM
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:
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