Python Function to Swap List Elements: f3(lst, i)
This code defines a Python function called f3(lst, i) that swaps two consecutive elements in a list.
def f3(lst, i):
lst[i] = lst[i + 1]
return lst
The function takes a list lst and an index i as input. It then assigns the value of the element at index i + 1 to the element at index i, effectively swapping their positions. Finally, the modified list is returned.
Explanation:
lst[i] = lst[i + 1]This line is the core of the function. It takes the value of the element at indexi + 1and assigns it to the element at indexi, effectively swapping their positions.return lstThis line returns the modified list after the swap has been performed.
Example Usage:
my_list = [1, 2, 3, 4, 5]
index = 2
result = f3(my_list, index)
print(result) # Output: [1, 2, 3, 3, 5]
In this example, the element at index 2 (which is 3) is swapped with the element at index 3 (also 3). The resulting list is [1, 2, 3, 3, 5].
原文地址: http://www.cveoy.top/t/topic/4fd 著作权归作者所有。请勿转载和采集!