Python: Change the position of every n-th value with the (n+1)th in a list
Python List: Exercise - 38 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-38.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics