Pointers in python?

Joined
Jul 20, 2023
Messages
56
Reaction score
2
Is there any way to get a variable to act like a pointer in python? Heres a little code to describe the gist of what Im trying to do.
Python:
name = 'Matt'
score = 0
player = {'name': name, 'score': score}  # This is what I want to act as a pointer
# ******** FAKE GAME **********
score += 10  # 10 points added to score
print(player)  # This will not print out the updated score

I know the correct way to go about this is to make it an object of a class but this is just a random example. Its not really exactly what Im doing. In what I am writing it doesnt make sense to make a class for just the one or two variables that Im trying to reference. This is something I've wished I had the ability to do quite a few times. It would be really nice. Any modules or anything that can help with this or tricks or anything?
 
Joined
Jul 4, 2023
Messages
474
Reaction score
58
AFAIK in python, variables are references to objects, and when you assign a variable to another, it essentially points to the same object. However, in your example, you are creating a dictionary, and modifying the score variable won't automatically update the dictionary since dictionaries are immutable. If you want to achieve something similar to a pointer in python, you might want to use a mutable object for example like a list.

[ working code on-line ]
Python:
name = 'Matt'
score = [0]  # Using a list to hold a mutable object
player = { 'name': name, 'score': score }

# ******** FAKE GAME **********
score[0] += 10  # 10 points added to score
print(player)  # This will print out the updated score

or

it is not simpler to change the field in the dictionary directly ...
[ working code on-line ]
Python:
player = { 'name': '', 'score': 0 }

# ******** FAKE GAME **********
player['name'] = 'Matt'
player['score'] += 10  # 10 points added to score
print(player)  # This will print out the updated player data
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top