How to repeat only a certain element in a list?

Junkrat :

Assuming a list as follows:

article = ['a', 'b', 'c', 'd']

and a variable named times

Now, based on the value of the variable times, I want to repeat just the element 'a' in the article list that many times.

For example:

If times = 2,

the desired output is

article = ['a', 'a', 'b', 'c', 'd']

Similarly, if times = 3,

the desired output is

article = ['a', 'a', 'a', 'b', 'c', 'd']

I tried doing:

[['a']*times, 'b', 'c', 'd']

But it gives me a list within a list as follows:

[['a', 'a'], 'b', 'c', 'd']

How can this be done?

jezrael :

Use + for join lists:

['a']*times + ['b', 'c', 'd']

In numpy is possible use numpy.repeat with numpy.concatenate:

article = ['a', 'b', 'c', 'd']
times = 3
b = np.concatenate([np.repeat(['a'], times), ['b', 'c', 'd']]).tolist()
print(b)
['a', 'a', 'a', 'b', 'c', 'd']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350492&siteId=1