Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a loop in Python to name variables

How do I use a loop to name variables? For example, if I wanted to have a variable double_1 = 2, double_2 = 4 all the the way to double_12 = 24, how would I write it?

I get the feeling it would be something like this:

for x in range(1, 13):
    double_x = x * 2 
    # I want the x in double_x to count up, e.g double_1, double_2, double_3

Obviously, this doesn't work, but what would be the correct syntax for implementing the looped number into the variable name? I haven't coded for a while, but I do remember there was a way to do this.

like image 824
davenz Avatar asked Nov 28 '12 10:11

davenz


Video Answer


2 Answers

Use a dictionary instead. E.g:

doubles = dict()

for x in range(1, 13):
    doubles[x] = x * 2

Or if you absolutely must do this AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING, you can assign to locals() as to a dictionary:

>>> for x in range(1, 13):
...     locals()['double_{0}'.format(x)] = x * 2
... 
>>> double_3
6

There never, ever should be a reason to do this, though - since you should be using the dictionary instead!

like image 140
Kimvais Avatar answered Oct 12 '22 11:10

Kimvais


expanding my comment: "use a dict. it is exactly why they were created"

using defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)

using normal dict:

>>> d = {}

the rest:

>>> for x in range(1, 13):
    d['double_%02d' % x] = x * 2


>>> for key, value in sorted(d.items()):
    print key, value


double_01 2
double_02 4
double_03 6
double_04 8
double_05 10
double_06 12
double_07 14
double_08 16
double_09 18
double_10 20
double_11 22
double_12 24
like image 22
Inbar Rose Avatar answered Oct 12 '22 12:10

Inbar Rose