How do I duplicate elements in a lists such that they repeat?
Input: ListA = [1,2,3,4,5,6,7,8,9]
Output: ListA = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9]
How do I duplicate elements in a lists such that they repeat?
Input: ListA = [1,2,3,4,5,6,7,8,9]
Output: ListA = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9]
We can use np.repeat()
ListA = [1,2,3,4,5,6,7,8,9]
ListA = np.repeat([1,2,3,4,5,6,7,8,9], 2)
ListA
Output
array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9])
Possibly the easiest way with the sorted list given is:
ListA = sorted(ListA + ListA)
... but this does assume that the original ListA was sorted. Otherwise you can do it in a procedural fashion:
ListAcopy = []
for el in ListA:
ListAcopy.extend([el,el])
ListA = ListAcopy
or through a two-layer zip list comprehension
ListA = [item for pair in zip(ListA,ListA) for item in pair]