w3resource

Python: Insert a specified element in a given list after every nth element

Python List: Exercise - 178 with Solution

Write a Python program to insert a specified element in a given list after every nth element.

Sample Solution:

Python Code:

def inset_element_list(lst, x, n):
    i = n
    while i < len(lst):
        lst.insert(i, x)
        i+= n+1
    return lst

nums = [1, 3, 5, 7, 9, 11,0, 2, 4, 6, 8, 10,8,9,0,4,3,0]
print("Original list:")
print(nums)
x = 20
n = 4
print("\nInsert",x,"in said list after every",n,"th element:")
print(inset_element_list(nums, x, n))

chars = ['s','d','f','j','s','a','j','d','f','d']
print("\nOriginal list:")
print(chars)
x = 'Z'
n = 3
print("\nInsert",x,"in said list after every",n,"th element:")
print(inset_element_list(chars, x, n))

Sample Output:

Original list:
[1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8, 10, 8, 9, 0, 4, 3, 0]

Insert 20 in said list after every 4 th element:
[1, 3, 5, 7, 20, 9, 11, 0, 2, 20, 4, 6, 8, 10, 20, 8, 9, 0, 4, 20, 3, 0]

Original list:
['s', 'd', 'f', 'j', 's', 'a', 'j', 'd', 'f', 'd']

Insert Z in said list after every 3 th element:
['s', 'd', 'f', 'Z', 'j', 's', 'a', 'Z', 'j', 'd', 'f', 'Z', 'd']

Pictorial Presentation:

Python List: Insert a specified element in a given list after every nth element.

Flowchart:

Flowchart: Insert a specified element in a given list after every nth element.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find common elements in a given list of lists.
Next: Write a Python program to create the largest possible number using the elements of a given list of positive integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Decapitalizes the first letter of a string:

Example:

def tips_decapitalize(s, upper_rest=False):
  return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
print(tips_decapitalize('PythonTips'))
print(tips_decapitalize('PythonTips', True)) 

Output:

pythonTips
pYTHONTIPS

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook