Write a Python program to change the position of every n-th value with the (n+1)th in a list. Sample list: [0,1,2,3,4,5] Expected Output: [1, 0, 3, 2, 5, 4]
Answers
def change_pos(my_list):
for i in range(0,len(my_list),2):
my_list[i],my_list[i+1]=my_list[i+1],my_list[i]
return my_list
my_list=[0,1,2,3,4,5]
print(change_pos(my_list))
Answer:
def change_pos(lst):
for i in range(0, len(lst)-1, 2):
lst[i], lst[i+1] = lst[i+1], lst[i]
return lst
# Sample list
my_list = [0,1,2,3,4,5]
# Change the position of every n-th value with the (n+1)th
result = change_pos(my_list)
# Print the result
print(result)
Explanation:
This program defines a function called "change_pos()" that takes a list as an input. The function uses a for loop to iterate through the list, starting at the 0th index and incrementing by 2 each time. Inside the for loop, the function uses tuple unpacking to swap the n-th value with the (n+1)th value. Then it returns the modified list.
In the main function, the program creates a sample list and calls the change_pos() function passing the sample list as an argument. It then prints the modified list as a result.
The expected output of this program is [1, 0, 3, 2, 5, 4].
More question and answers:
https://brainly.in/question/13890400
https://brainly.in/question/50127158
#SPJ3