Table of Contents

Incrementing Elements in a List

Example Description
Learn how to increment the elements of a list in Python. See the effect of passing a list as a parameter to a function and modifying it.

Introduction:

This Python code demonstrates how to increment the elements of a list by a certain amount. The code defines a function called “increment” that takes a list as an argument and adds 5 to each element in the list. The main function creates a list and then calls the “increment” function, passing the list as a parameter. The code shows the list before and after the function call to demonstrate the effect of modifying a list in a function.

Code:

#Function to increment the elements of the list passed as argument
def increment(list2):
 for i in range(0,len(list2)): 
 #5 is added to individual elements in the list
  list2[i] += 5 
 print('Reference of list Inside Function',id(list2))
#end of function
list1 = [10,20,30,40,50] #Create a list
print("Reference of list in Main",id(list1))
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)

Logic:

  1. The function “increment” takes a list (list2) as an argument.
  2. It iterates through the elements of the list using a for loop.
  3. Inside the loop, it adds 5 to each element in the list using the += operator.
  4. After modifying all the elements, it prints the reference of the modified list (list2) using the id() function.
  5. The main function creates a list called “list1” with initial values.
  6. It prints the reference of the original list using the id() function.
  7. It prints the original list before calling the “increment” function.
  8. It calls the “increment” function, passing the “list1” as a parameter.
  9. The “increment” function modifies the elements of “list1”.
  10. It prints the modified list after the function call.

Output:

>> Reference of list in Main 140446246092360

>> The list before the function call

>> [10, 20, 30, 40, 50]

>> Reference of list Inside Function 140446246092360

>> The list after the function call

>> [15, 25, 35, 45, 55]

The output shows the reference (id) of the original list before the function call and the reference of the modified list inside the function call. It also displays the original list before calling the function and the modified list after the function call. The elements of the list have been incremented by 5.