Python3 program to swap elements
Question:
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
i dont understand why "pos2-1" is used here why did they use minus one why doesn’t it work without minus one??
Answers:
The reason why it takes "Pos2-1" is, the list index starts with 0(zero)
So
index List
0 23
1 65
2 19
3 90
So if you don’t give the "-1", then the function will take the index values of 1 and 3, which is 65 and 90.
If you find the explanation useful, accept it and vote for it
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
i dont understand why "pos2-1" is used here why did they use minus one why doesn’t it work without minus one??
The reason why it takes "Pos2-1" is, the list index starts with 0(zero)
So
index List
0 23
1 65
2 19
3 90
So if you don’t give the "-1", then the function will take the index values of 1 and 3, which is 65 and 90.
If you find the explanation useful, accept it and vote for it