Home > OS >  how to add value after every 2 elements in Python List? [duplicate]
how to add value after every 2 elements in Python List? [duplicate]

Time:10-03

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

CodePudding user response:

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']
  • Related