I have been studying functions in python and how the variables are passed by values and not reference since its a lot safer
I don't know where you read this, but that's just complete bullshit.
if that is the way it is
It isn't.
then why do the variable passed around have the same ID.
Because they point to the same object, obviously.
I initially used x=3 but then I read that how python caches variables from -5 to 256
That's a CPython implementation detail, and the exact values depend on the CPython version etc. But anyway, you can test this with any number you want, and actually just any type, the result will still be the same.
so I used 500 but it still shows the same id. If they have the same doesn't it mean that it is the same object passed around?
id(obj)
, by definition, returns the object's unique identifier (actually the memory address in CPython but that's also an implementation detail), so by definition, if two objects have the same id, then they are indeed the very same object.
NB : "unique" meaning that for the current process, no other object will have the same id at the same time - once an object is garbage-collected, it's id can be reused.
FWIW, using a mutable object, it's quite easy to find out that it's not passed "by value":
def foo(lst):
lst.append(42)
answers = []
for i in range(10):
print("{} - before: {}".format(i, answers))
foo(answers)
print("{} - after: {}".format(i, answers))
0 - before: []
0 - after: [42]
1 - before: [42]
1 - after: [42, 42]
2 - before: [42, 42]
2 - after: [42, 42, 42]
3 - before: [42, 42, 42]
3 - after: [42, 42, 42, 42]
4 - before: [42, 42, 42, 42]
4 - after: [42, 42, 42, 42, 42]
5 - before: [42, 42, 42, 42, 42]
5 - after: [42, 42, 42, 42, 42, 42]
6 - before: [42, 42, 42, 42, 42, 42]
6 - after: [42, 42, 42, 42, 42, 42, 42]
7 - before: [42, 42, 42, 42, 42, 42, 42]
7 - after: [42, 42, 42, 42, 42, 42, 42, 42]
8 - before: [42, 42, 42, 42, 42, 42, 42, 42]
8 - after: [42, 42, 42, 42, 42, 42, 42, 42, 42]
9 - before: [42, 42, 42, 42, 42, 42, 42, 42, 42]
9 - after: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]