-4

It's a simple question, but I can't find the solution. How can I do it with for loop? (In a shorter way.)

nfo1 = str(nfolist[0])
nfo2 = str(nfolist[1])
nfo3 = str(nfolist[2])
nfo4 = str(nfolist[3])
nfo5 = str(nfolist[4])
nfo6 = str(nfolist[5])
nfo7 = str(nfolist[6])
nfo8 = str(nfolist[7])
nfo9 = str(nfolist[8])
nfo10 = str(nfolist[9])
nfo11 = str(nfolist[10])

2 Answers2

1
for i in range(11):
  locals()[f'nfo{i + 1}'] = str(nfolist[i])

but it’s a bit ugly

Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29
0

Instead you can use a dictionary:

nfo = {}
for x in range(11):
  nfo['nfo'+str(x)]=str(nfolist[x])

The dictionary nfo:

{'nfo0': '0',
 'nfo1': '1',
 'nfo2': '2',
 'nfo3': '3',
 'nfo4': '4',
 'nfo5': '5',
 'nfo6': '6',
 'nfo7': '7',
 'nfo8': '8',
 'nfo9': '9',
 'nfo10': '10'}

To get a value from the dict (suppose want nfo['nfo4']):

print(nfo['nfo4'])
Wasif
  • 14,755
  • 3
  • 14
  • 34