How to update an already existing array by accessing it by a variable with the exact same name assigned to it

43 Views Asked by At

i declared an array earlier on in the program and then assigned a variable to the exact same array name . I later on attempted to change a value within the array using the variable name i declared but the array is not updating.

 J2 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] #i defined the array J2.
appointment = 'J2' # then i declared the variable appointment to the string J2
time = 3 # and i assigned the variable time=3. 
appointment[time] = 6 #i tried to input 6 into the J2 at index 3 by typing appointment[time]=6 

But when and then printing the array J2, i keep on getting an unchanged array`

1

There are 1 best solutions below

0
TheHungryCub On

when you use a string to refer to a variable name, it doesn't directly access the variable itself. Instead, you can achieve this using a dictionary to store your arrays with their corresponding names.

Try this:

Solution 1:

J2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
arrays = {'J2': J2}
appointment = 'J2'

# Assign the variable time=3
time = 3

# Update the value in the array using the dictionary
arrays[appointment][time] = 6

print(arrays['J2'])

Output:

[0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Solution 2 (as per suggested in comment):

J2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

appointment = 'J2'

time = 3

# Update the value in the array using globals()
globals()[appointment][time] = 6

print(J2)

Output:

[0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]