Table of Contents

Python Function to Increment Elements of a List

Example Description
This Python code uses a function to increment the elements of a list and shows the before/after changes in the list ID.

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:

  1. Define a function called “increment” that takes a list as an argument.
  2. Print the ID of the list inside the function before any assignment.
  3. Assign a new list [15, 25, 35, 45, 55] to the argument list2.
  4. Print the ID of the list after the assignment.
  5. Print the new list inside the function.
  6. Create a list called “list1” with values [10, 20, 30, 40, 50].
  7. Print the ID of the list before the function call.
  8. Print the list before the function call.
  9. Call the “increment” function with “list1” as the parameter.
  10. Print the ID of the list after the function call.
  11. 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]