Home > Blockchain >  Repeat a list's elements in the same order
Repeat a list's elements in the same order

Time:05-06

I have a list, and I want to repeat its elements in the same order.

I want to create bg using sl.

# small list
sl = [10,20]
# from small list, create a big list
bg = [10,10,20,20]

I tried:

bg = [[i,j] in for i,j in zip([[sl[0]]*2,[sl[1]]*2])]

But this gives me:

 bg = [[10,20],[10,20]]

How can I get the desired output?

CodePudding user response:

import numpy as np
s1 = [10,20]
s2 = np.array(s1).repeat(2)
print(list(s2)) # [10, 10, 20, 20]

I could not resist the urge to use numpy in such operations. With this function you can repeat not only for single dimensional cases but also in case of matrix or higher order tensors as well.

CodePudding user response:

Here is an approach using itertools:

from itertools import repeat, chain
repetitions = 2

list(chain.from_iterable(repeat(item, repetitions) for item in sl))

You can also use a list comprehension, though it's important to note that using multiple for clauses in a list comprehension is considered poor style by some:

[item for item in sl for _ in range(repetitions)]

This outputs:

[10, 10, 20, 20]

CodePudding user response:

You can use itertools.chain and zip:

from itertools import chain
out = list(chain.from_iterable(zip(*[sl]*2)))

Output:

[10, 10, 20, 20]

Since you tagged it pandas, you could use repeat as well:

out = pd.Series(sl).repeat(2)

Output:

0    10
0    10
1    20
1    20
dtype: int64

CodePudding user response:

A very simple approach might be:

sl = [10,20]
# from small list, create a big list
bg = []
for ele in sl:
    bg.append(ele)
    bg.append(ele)
print(bg)

To make it more generic and incase of more repetitions, you can do:

def append_lst(lst, val):
    lst.append(val)

sl = [10,20]
# from small list, create a big list
bg = []
noOfRep = 2
for ele in sl:
    for _ in range(noOfRep):
        append_lst(bg, ele)
    
print(bg)

Output:

[10, 10, 20, 20]

CodePudding user response:

l1 = [10,20]
l2 = l1
l1.extend(l2)

output:

value of l1:
[10,20,10,20]
  • Related