How to repeat only a certain element in a list?

Viewed 187

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?

5 Answers

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

Similarly to your approach, you could unpack the inner list with:

times = 2

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

You could use slicing and list concatenation for this as well:

>>> article[:1] * 2 + article[1:]
['a', 'a', 'b', 'c', 'd']

[:1] slices up until but not including the 1st index. [1:] slices everything and including the 1st index.

Here's a nice function you can use if the article and times variables are already defined (or they come from a function you don't want to change). This also has the advantage that the element you want to repeat can be in an arbitrary index:

from typing import List, TypeVar

T = TypeVar('T')


def repeat_idx(ls: List[T], x: int, i: int) -> List[T]:
    """Return a new list with the element in the given index repeated x times.

    Args:
        ls: The list which element to repeat.
        x: How many times to repeat the element.
        i: The index of the element to repeat.

    """
    return ls[:i] + [ls[i]]*x + ls[i + 1:]


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

print(repeat_idx(article, times, 0))
print(repeat_idx(article, times, 1))
print(repeat_idx(article, times, 3))

Output:

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

You can use for loop here:

times = 3
index = 2
l = ['a','b','c','d']

for i in range(times):
    l.insert(index,l[index])

print(l)

The 'index' variable is the index of the element which you want to repeat.

Related