0

I have defined a variable as below:

time = "0915"

now next I want to create another variable naming it as follows:

x_0915 = "some value" #### idea is to have previously defined variable value in this new variable name itself

how do I make it automatic as I will be having this kind of multiple situations?

so the task is I want to concatenate "x" with the previously defined variable value and use it as a name for the new variable.

4
  • have you tried this? Commented Jun 26, 2022 at 7:27
  • 3
    You shouldn't do this. Use a container, like a list or a dict Commented Jun 26, 2022 at 7:27
  • 2
    Avoid dynamic variable. Use a dict only Commented Jun 26, 2022 at 7:28
  • 1
    How would use x_0915 if it depends of the value of time ? Commented Jun 26, 2022 at 7:29

1 Answer 1

2

Use a dictionary instead of defining dynamic variables and creating a mess.

time = ["0915", "0920", "0925"]
a = {}
for i in time:
    a[f"x{i}"] = "some value"

print(a)

Output

{'x0915': 'some value', 'x0920': 'some value', 'x0925': 'some value'}
Sign up to request clarification or add additional context in comments.

5 Comments

Please paste text, not image of it
@azro I changed it, But is there any reason for the text? because image is also clear
Text is as clear as image, responsive on different device, copyable, doesn't request to load, it, will always be accessible. And why put an image a text :)
I can't paste an image into my IDE and get python to run the code.
Dictionary comprehensions can clean this up a bit: a = {f"x{i}": "some value" for i in time}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.