0

I have some list like:

all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]  

And I want to print it out like

 num = 0
 print(all+num)

But it didn't work. How to add a character or a number to a variable name?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
wayne64001
  • 399
  • 1
  • 3
  • 13
  • 1
    Why not have a `dict` named `all` with keys `0`, `1`, ... Then you can get and set values from the dictionary with `num` easily. (Although bear in mind that `all` is a built-in function.) – TrebledJ Jan 09 '19 at 14:02

3 Answers3

1

Hmm, I am pretty sure that you do not need nor really want it, but Python has provision for computing a variable name. Simply it is a rather advanced feature and the normal way is to use mappings (dict) or sequence (list or tuple) containers.

Here, you would use:

all = []
all.append([['mortem' 'cliffi' 'gear' 'lerp' 'control']])
all.append([['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']])

num = 0
print(all[0])

BTW, this syntax is weird, because you are essentially concatenating adjacent litteral string...

But if you really, really need it you can build a interpolator of variables:

def getvar(name):
    if name in locals():
        return locals()[name]
    elif name in globals():
        return globals()[name]
    else:
        raise NameError(repr(name) + ' is not defined')

You can then do:

all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]

num = 0

print(getvar("all%d" % num))

and get as expected:

[['mortemcliffigearlerpcontrol']]
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You can use eval() for that.

eval('print(all{})'.format(num))

But this is really bad style. Don't do this. You should refactor your code and use for loops to go through your lists e.g.

all = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all.append(['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']) 

for l in all:
    print(l)
nauer
  • 690
  • 5
  • 14
0

Leaving aside how bad an idea it might be (probably really bad), variable names are just keys in a Python dict. A one-line solution might be:

vars()[new_name] = vars().pop(old_name)

for global variables, and

vars(some_obj)[new_name] = vars(some_obj).pop(old_name)

for variables of some_obj object.

jkm
  • 704
  • 4
  • 7