Table of Contents
show
- In Python, arguments are passed by reference
- If any changes are done in the parameter which refers within the function, then the changes also reflect back in the calling function
- When a list to a function is passed, the function gets a reference to the list
- Passing a list as an argument actually passes a reference to the list, not a copy of the list
- Since lists are mutable, changes made to the elements referenced by the parameter change the list that the argument is referencing
Example
Removal
def remove1(flist):
ritem=int(input('Enter the item to remove:'))
flist.remove(ritem)
n=int(input("Enter total number of elements"))
list1 = [ ]
for i in range(n):
a = int(input("enter the values"))
list1.append(a)
print("Originally, Elements in List:", list1)
remove1(list1)
print("After removing the values in list:",list1)
Output
Enter total number of elements 5
enter the values 2
enter the values1
enter the values4
enter the values5
enter the values6
Originally, Elements in List: [2, 1, 4, 5, 6]
Enter the item to remove: 1
After removing the values in list: [2, 4, 5, 6]
Sumwithn
def sumwithn(flist):
for i in range(len(flist)):
flist[i] = flist[i] + 5
n=int(input("Enter total number of elements"))
list1 = [ ]
for i in range(n):
a = int(input("enter the values"))
list1.append(a)
print("Originally, Elements in List:", list1)
sumwithn(list1)
print('After function call:',list1)
Output
Enter total number of elements 5
enter the values 10
enter the values 0
enter the values 3
enter the values 1
enter the values 20
Originally, Elements in List: [10, 0, 3, 1, 20]
After function call: [15, 5, 8, 6, 25]
Insert
def U_insert(flist):
val=int(input("Enter the value to insert:"))
pos = int(input("Enter the positon to insert the value:"))
flist.insert(pos,val)
n=int(input("Enter total number of elements"))
list1 = [ ]
for i in range(n):
a = int(input("enter the values"))
list1.append(a)
print('Before function call:', list1)
U_insert(list1)
print('After function call:',list1)
Output
Enter total number of elements 5
enter the values 10
enter the values 1
enter the values 2
enter the values 0
enter the values 3
Before function call: [10, 1, 2, 0, 3]
Enter the value to insert: 100
Enter the positon to insert the value: 4
After function call: [10, 1, 2, 0, 100, 3]
Views: 0