-1

I want to add a specific value after every two elements in List. Ex:

zz = ['a','b','c','d','f']

i want to add the word: "Hero" and the final look will be :

zz = ['a','b','Hero','c','d','Hero','f']

i tried to use function insert to put an value in a specific index but it doesnt work this is my code:

zz = ['a','b','c','d','f']
count = 0
for x in zz:
    if count == 2:
        zz.insert(count,"Carlos")
    print(x)
    count+=1

i think it is far away from the solution im still newbie in python

BadPiggie
  • 5,471
  • 1
  • 14
  • 28
Learn377
  • 11
  • 2
  • 1
    Does this answer your question? [Insert element in Python list after every nth element](https://stackoverflow.com/questions/31040525/insert-element-in-python-list-after-every-nth-element) – user202729 Oct 02 '21 at 12:18
  • Although using `enumerate` and "other complex functions" may not be in your best interest to learn. First figure out with a pen and paper how you do it manually, then implement that into Python instead. – user202729 Oct 02 '21 at 12:19

1 Answers1

0

You can try this:

letters = ['a','b','c','d','f']
n = 2
word = 'Hero'
val_list = [x for y in (letters[i:i+n] + [word] * (i < len(letters) - n) for i in range(0, len(letters), n)) for x in y]

print(val_list)

Here, used nested comprehensions to flatten a list of lists([item for subgroup in groups for item in subgroup]), sliced in groups of n with word added if less than n from end of list.

Another alternative:

letters = ['a','b','c','d','f']
n = 2
word = 'Hero'

for i in range(n, len(letters) + n, n + 1):
    letters.insert(i, word)

print ( letters )

Output:

['a', 'b', 'Hero', 'c', 'd', 'Hero', 'f']
Sabil
  • 3,750
  • 1
  • 5
  • 16