Code Bug Fix: Incrementing the list title name with numbers in Python [duplicate]

Original Source Link

I am unable to increment the number in my list name as i need a list name going from 0 to 24, i’ve tried to use the concatenation but it didn’t work.

Folllowing is my example code:

d.last0 = [0,0]
d.last1 = [0,0]
d.last2 = [0,0]
d.last3 = [0,0]
d.last4 = [0,0]
d.last24 = [0,0]

As you see, this intialization goes till 24, what i want to do to bring this under loop so i can make the code more faster and efficient, but when i call this as


it didn’t return any data, also tried with this:


Use below dictionary code to meet your requirement,

d={}     # declare the dictionary
d['last0'] = [0,0]  #assigning the values to dictionary
print(d)  # verify for the values

# to meet your requirement to have 24 values increment, loop and update the dict
for i in range(25):


A way to do this is by using hash tables (dictionaries). These allow you to use a key and associate data with that key. Here is your problem solved with a dictionary in python:

d = {}
for i in range(25):
    d['last' + str(i)] = [0,0]

print(d['last24']) # prints [0,0]

If you insist on having 25 different variables, you can use the globals() keyword in python, which you can edit like this:

for i in range(25):
   globals()['last' + str(i)] = [0,0]

print(last24) # prints [0,0]

Tagged : /

Leave a Reply

Your email address will not be published. Required fields are marked *