Python Forum

Full Version: Create, assign and print variables in loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I want to create and assign a value to a variables in a for loop and name the variable in the loop. This works as intended. Afterwards, I would like to print the variables something like:
a = 3
source=(0.1, 0.2, 0.3)
for n in range (a):
    exec("var"+str(n)+" = source[n]")
    print('var'+str(n))
However, I end up with:
var0
var1
var2
Whereas I want output corresponding to this:
print(var0)
print(var1)
print(var2)
How do I change the code accordingly?
You really shouldn't be trying to dynamically create variables like that. For a start, it's just over-complicated and you'll find your code becomes hard to maintain. Why exactly do you want to do it, i.e. what problem are you trying to solve?
Well the reason is that "var" + str(n) creates a string, not a variable.

But yeah, you need to reconsider your approach.
as advised - use proper data structure - list/dict, don't create names dynamically
First of all, thanks for you feedback. Since I am new to Python, there is a lot to learn:

  1. Despite the fact that my proposal is not really suited, what would be the necessary adjustment such that I obtain the desired result?
  2. I have a number of variables that may change, here "a". This number always corresponds to the number of elements in "sources". I need to create a variable that contains the value in the list "sources" and its position in the name of the variable. What would be the right way to solve this problem?
as already said - use proper data structure

# sources is a tuple
sources=(0.1, 0.2, 0.3)

# access elements in tuple/list by index
print(sources[0])
print(sources[2])

# you can assign to a name
foo = sources[1]
# use that name
print(foo)


# using dict, created with dict comprehension
spam = {f'a{idx}':num for idx, num in enumerate(sources)}
print(spam)
# access elements by key
print(spam.get('a0'))
print(spam['a1'])
print(spam.get('a5', 'wrong key'))


# using dict, created another way
spam = {}
for idx, num in enumerate(sources):
    spam[f'a{idx}'] = num 
print(spam)
# access elements by key
print(spam.get('a0'))
print(spam['a1'])
print(spam.get('a5', 'wrong key'))
Output:
0.1 0.3 0.2 {'a0': 0.1, 'a1': 0.2, 'a2': 0.3} 0.1 0.2 wrong key {'a0': 0.1, 'a1': 0.2, 'a2': 0.3} 0.1 0.2 wrong key
This may be the proper way to code the problem, but it just confuses me a lot.

Is it really not possible to use what I have suggested? It may appear wrong to you, but I would like to know it anyway.
Why does it confuse you?

It would be possible to do what you wanted, but you'd have to make more use of exec (or eval, I guess). What are the problems with that? There are at least two:

1. Those functions allow any arbitrary Python expression to be entered in a string. So, if data came in from a user, that could present a security risk (in the same way that SQL injection does).

2. You'd end up having a lot of code written in the strings you pass to those functions. That's quickly going to become unreadable as you'll lose the benefits of syntax highlighting in your editor/IDE, not to mention that you'll have lots of concatenation which you won't if you're just writing Python code in the file.
read http://stupidpythonideas.blogspot.com/20...reate.html

still, you will need to learn how to work with container types like list/tuple/dicts, etc. it's a fundamental, you cannot progress beyond basics without it
The assignment of the values to the variables (which in fact are scalars) works just fine. I just would like to display the values of these scalars within the loop. I get it, it is wrong. Still it is what I want to do
Pages: 1 2