Python: Change the position of every n-th value with the (n+1)th in a list
Swap Every n-th and (n+1)th Values
Write a Python program to change the position of every n-th value to the (n+1)th in a list.
Sample Solution:
Python Code:
# Import the 'zip_longest,' 'chain,' and 'tee' functions from the 'itertools' module
from itertools import zip_longest, chain, tee
# Define a function named 'replace2copy' that takes a list 'lst' as input and returns a new list with elements rearranged
def replace2copy(lst):
# Use the 'tee' function to create two independent iterators from 'lst'
lst1, lst2 = tee(iter(lst), 2)
# Use 'zip_longest' to pair elements from 'lst' with an offset to create a new sequence
# Chain the pairs together and convert them to a list
return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))
# Define a list 'n' containing numeric elements
n = [0, 1, 2, 3, 4, 5]
# Call the 'replace2copy' function with 'n' as the argument and print the result
print(replace2copy(n))
Sample Output:
[1, 0, 3, 2, 5, 4]
Flowchart:
Python Code Editor:
Previous: Write a Python program to find common items from two lists.
Next: Write a Python program to convert a list of multiple integers into a single integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics