Python Forum
Create, assign and print variables in loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create, assign and print variables in loop
#1
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?
Reply
#2
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?
Reply
#3
Well the reason is that "var" + str(n) creates a string, not a variable.

But yeah, you need to reconsider your approach.
Reply
#4
as advised - use proper data structure - list/dict, don't create names dynamically
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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?
Reply
#6
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
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.
Reply
#8
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.
Reply
#9
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create X Number of Variables and Assign Data RockBlok 8 928 Nov-14-2023, 08:46 AM
Last Post: perfringo
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,685 Nov-07-2023, 09:49 AM
Last Post: buran
Question How create programmatically variables ? SpongeB0B 6 1,305 Aug-19-2023, 05:10 AM
Last Post: SpongeB0B
  How to print variables in function? samuelbachorik 3 902 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,482 Jul-27-2022, 08:50 PM
Last Post: rob101
  Create array of values from 2 variables paulo79 1 1,082 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,479 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  How to create 2 dimensional variables in Python? plumberpy 5 1,848 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  how to use 3 variables python loop evilcode1 2 1,667 Nov-12-2021, 11:43 AM
Last Post: jamesaarr
  How can I assign "multiple variables" to a single "value"? Psycpus 2 1,852 Oct-04-2021, 03:29 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020