Passing Integers vs Lists in Python Functions

What really happens when we pass an integer vs a list to a function? In Python, passing an integer to a function does not behave the same way as passing a list. Let’s see why. Example 1: Passing an Integer def change_value(x): x = x + 10 return x num = 5 change_value(num) print(num) ➡️Output: 5 At first glance, this might seem confusing. Here’s what actually happens: 1. num references the integer object 5 in memory. 2. When we call change_value(num), the value 5 is passed to the function. 3. Inside the function, a new local variable x is created, referencing the same object 5. At this moment: num → 5 x → 5 Now comes the important part: x = x + 10 Integers in Python are immutable, meaning they cannot be modified after creation. So Python does not change the value 5. Instead: 1. It calculates 5 + 10. 2. It creates a new integer object 15. 3. It makes x reference this new object. Now: num → 5 x → 15 The original 5 is still in memory, unchanged. This is called rebinding (the variable x was redirected to a new object). And because we did not assign the returned value back to num: ❌ num = change_value(num) ➡️ num remains 5. Example 2: Passing a List def add_item(lst): lst.append(10) numbers = [1, 2, 3] add_item(numbers) print(numbers) ➡️Output: [1, 2, 3, 10] Why did this one change? Because lists are mutable. When we pass numbers to the function: 1. lst references the same list object. 2. When we call lst.append(10), we modify the same object in place. No new list is created. Before: numbers → [1, 2, 3] After: numbers → [1, 2, 3, 10] The variable still points to the same object, but that object was directly modified. This is called modification (in place). 💡 The Core Difference When passing data to a function in Python: • If the object is immutable (like int),the function cannot modify it. Any change creates a new object (rebinding). • If the object is mutable (like list),the function can modify the same object in place. That is why the integer stayed 5, while the list was successfully updated. Understanding this difference is essential to understanding how Python handles memory and variable references. #Python #SoftwareDevelopment #CodingTips #MachineLearning #AI

To view or add a comment, sign in

Explore content categories