206

For example purposes...

for x in range(0,9):
    string'x' = "Hello"

So I end up with string1, string2, string3... all equaling "Hello"

cs95
  • 379,657
  • 97
  • 704
  • 746
Takkun
  • 8,119
  • 13
  • 38
  • 41
  • 42
    The answer is that you don't want to do this. Use a list instead. – Sven Marnach May 31 '11 at 00:55
  • 2
    If this is where you want to use it you can have `x = ["Hello" * 9]` then access it by `x[0], x[1] ...` If you want to use it in a different way I think you'll have to give us some more code background. – James Khoury May 31 '11 at 00:56
  • 3
    If I ever have power over a language then using numbers in variable names will give `SyntaxError: Use a data structure.` ;-) – Jochen Ritzel May 31 '11 at 01:08
  • 1
    and don't forget your string0 ;) – wim May 31 '11 at 01:08
  • 12
    @James Khoury: That's not quite right. That would end up with `x` being a list containing a single element - the string "HelloHelloHelloHelloHelloHelloHelloHelloHello". I think you meant `x = ["Hello"] * 9`. –  May 31 '11 at 01:08
  • @Chrono Whoops! your right there. I should re-read my posts before I press enter ;) thanks. – James Khoury May 31 '11 at 02:15
  • [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html) – glglgl Jan 08 '19 at 13:35

9 Answers9

237

Sure you can; it's called a dictionary:

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!

Georgy
  • 12,464
  • 7
  • 65
  • 73
the wolf
  • 34,510
  • 13
  • 53
  • 71
  • 51
    This should not be marked as the correct answer because it's not; this is a dictionary, not a dynamic variable assignment, which is what the OP was asking for. – Ghost Sep 28 '20 at 17:09
  • 2
    It is the correct answer, because every time you think you need dynamic variable assignment, you should actually just use a dict. That's how I got here; and my code is now better because of this answer. – Herman Dec 11 '22 at 03:04
115

It is really bad idea, but...

for x in range(0, 9):
    globals()['string%s' % x] = 'Hello'

and then for example:

print(string3)

will give you:

Hello

However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • 4
    Can you elaborate on why this is a bad idea? – ajdigregorio Jul 08 '14 at 20:17
  • 11
    @paintedcones: First, _there should be one way to do it_, and using simple dictionaries is more natural. Using globals dictionary instead is a bad idea, because it also "implicitly" creates global variables or modifies them. Since both setting and modifying variables this way requires dictionary notation, there is no reason to use `globals()` instead of some simple `dict`. – Tadeck Jul 10 '14 at 14:25
  • There are a few situations when you do need to make a bunch of variables, x1, x2, x3, etc. But in most situations, using a dictionary really is the most appropriate thing to do. – DevilApple227 Jul 02 '16 at 21:54
  • Hello Tadeck, how can I create globals variables over a Json Array loop, using your method, please . (for item in enumerate(items):) . I haven't got the exact syntax. PLease, can you help me ? – harmonius cool Sep 01 '20 at 13:03
  • 10
    This should be marked as the correct answer, not the other one. The question was how to dynamically create variables, not "the most recommended way to achieve a similar objective". – Ghost Sep 28 '20 at 17:11
  • What if you want to define $string1$ to $n$ and use it to define equations inside a function and then solve it in python? Is this possible? – jpcgandre May 04 '22 at 18:00
  • how can you print each string in a loop? For example, how do you `print(string%s)` – Shōgun8 Nov 08 '22 at 00:37
  • it's the correct answer, not the other ones – TurboC Mar 27 '23 at 17:19
52

One way you can do this is with exec(). For example:

for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8

Here I am taking advantage of the handy f string formatting in Python 3.6+

Georgy
  • 12,464
  • 7
  • 65
  • 73
Collin W.
  • 537
  • 4
  • 3
  • 14
    Remember `exec` something something, black magic, attack vulnerabilities, bad stuff, but it does answer the question as asked. – psaxton Nov 06 '17 at 22:52
27

It's simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can't use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • Thank you!! I needed to choose the form among dictionary or list of dataframe. And since I needed to reorder the dataframe based on a certain value on the dataframe, I could not have used dictionary form. Yeah you are right! In some cases it is really pointless to create variable names! – Doo Hyun Shin Feb 13 '19 at 13:01
  • Useful when reading in multiple files into dataframes. – Carl Kirstein Jan 13 '22 at 15:10
17
for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Abhishek Rai
  • 376
  • 2
  • 7
12

Don't do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don't do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea

Aaron Goldman
  • 829
  • 9
  • 7
5

I would use a list:

string = []
for i in range(0, 9):
  string.append("Hello")

This way, you would have 9 "Hello" and you could get them individually like this:

string[x]

Where x would identify which "Hello" you want.

So, print(string[1]) would print Hello.

Lledargo
  • 102
  • 4
  • 1
    Unlike some languages, you can't assign to elements in a Python list that don't yet exist (you'll get a "list assignment index out of range" error). You may want to use `string.append("Hello")` instead. – Greg Hewgill May 31 '11 at 01:10
  • 1
    I should have known that, thank you for reminding me. It is fixed. – Lledargo May 31 '11 at 01:15
  • Your right, I was thinking of adding to the end of a string, not adding to an array. My apologies everyone. – Lledargo May 31 '11 at 01:26
  • Pedantically 'you would have 9 "Hello"' should be 'you would have 1 "Hello" 9 times'. It's the same string repeated, not nine difference strings. – Duncan May 31 '11 at 07:57
3

Using dictionaries should be right way to keep the variables and associated values, and you may use this:

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

But if you want to add the variables to the local variables you can use:

for i in range(9):
     exec('string%s = Hello' % i)

And for example if you want to assign values 0 to 8 to them, you may use:

for i in range(9):
     exec('string%s = %s' % (i,i))
Ashkan Mirzaee
  • 300
  • 4
  • 14
2

I think the challenge here is not to call upon global()

I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.

Here is an example - I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive - ping test) at any given branch and then perform some operations on them.

Here is my code:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

Output is:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07

Cumar Chan
  • 21
  • 3