Question: In Python, variable scope is further related to whether the data type is immutable or mutable. Consider the following examples. Copy the code and run

In Python, variable scope is further related to whether the data type is immutable or mutable. Consider the following examples. Copy the code and run then in the online interpretor https://www.programiz.com/python-programming/online-compiler/.

nums=77 nums2=nums def test(): nums2=99 print(nums2)

test() print(nums) print(nums2)

In this instance nums2 is changed within the function, but nums2 within the function is a local scope variable and different than the global scope version. When we return to the global scope and do the last two print statement, the printed values are 77, meaning the function did not change their values.

Now lets try the following with a list

nums=[1,2,3] nums2=nums def test(): nums2[0]=100 print(nums2)

test() print(nums) print(nums2)

In this case the function DOES change the first value within the list nums and nums2. All three print statements should print [100, 2, 3]. The difference is that a list is mutable and hence have a global scope.

Try running the two above sections of code. Place the outputs into the answer below.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!