Introduction:
This Python code demonstrates a function that takes a list as an argument and increments its elements. It shows the changes in the ID of the list before and after the function call.
Code:
#Function to increment the elements of the list passed as argument
def increment(list2):
print("\nID of list inside function before assignment:",
id(list2))
list2 = [15,25,35,45,55] #List2 assigned a new list
print("ID of list changes inside function after assignment:",
id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)
Logic:
- Define a function called “increment” that takes a list as an argument.
- Print the ID of the list inside the function before any assignment.
- Assign a new list [15, 25, 35, 45, 55] to the argument list2.
- Print the ID of the list after the assignment.
- Print the new list inside the function.
- Create a list called “list1” with values [10, 20, 30, 40, 50].
- Print the ID of the list before the function call.
- Print the list before the function call.
- Call the “increment” function with “list1” as the parameter.
- Print the ID of the list after the function call.
- Print the list after the function call.
Output:
>> ID of list before function call: [ID of list1]
>> The list before function call: [10, 20, 30, 40, 50]
>>
>> ID of list inside function before assignment: [ID of list1]
>> ID of list changes inside function after assignment: [ID of new list2]
>> The list inside the function after assignment is: [15, 25, 35, 45, 55]
>>
>> ID of list after function call: [ID of list1]
>> The list after the function call: [10, 20, 30, 40, 50]