Search code examples
pythonpointersmemoryreferencefor-in-loop

Can I access memory location and values ( pointers and reference ) for variables in a loop, in Python 3


my_num_1 = 10
my_num_2 = 20

# I want to assign value 5 to above two variables like this:

for num in [my_num_1, my_num_2]:
    num = 5

That won't work. So is there a way to do something like this pseudo code:

for num in [(address_of)my_num_1, (address_of)my_num_2]:
    (value_at)num = 5

The code and application is terrible I know. But is there a way to play around with pointers and (de)referencing in Python like this?


Solution

  • Assuming you're a beginner to Python

    What you want is a dictionary or a list. Use a dictionary if you need the variable names, but in this case a list is probably a better idea.

    Dictionary sample implementation:

    nums={
        "my_1": 10,
        "my_2": 20,
    } #Create a dictionary of your nums
    
    print(nums["my_1"]) #10
    print(nums["my_2"]) #20
    
    for num in nums: #Iterate through the keys of the dictionary
        nums[num] = 5 #and set the values paired with those keys to 5
    
    print(nums["my_1"]) #5
    print(nums["my_2"]) #5
    

    List sample implementation:

    nums = [10, 20] #Create a list and populate it with your numbers
    
    print(nums[0]) #10
    print(nums[1]) #20
    
    for num in range(len(nums)): #Keys for your list
        nums[num] = 5 #Set the values within the list
    
    print(nums[0]) #5
    print(nums[1]) #5
    

    Assuming you're a moderately advanced programmer

    You can mutate the globals() dict.

    my_num_1 = 10
    my_num_2 = 20
    
    print(my_num_1) #10
    print(my_num_2) #20
    
    for name in ("my_num_1", "my_num_2"): #Iterate through a tuple of your names
        globals()[name] = 5 #and mutate the globals dict
    
    print(my_num_1) #5
    print(my_num_2) #5