-2

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]
Moshe
  • 19
  • 5
  • Iterate over the list items and append each item twice to a new list. – wwii May 06 '21 at 23:12
  • Welcome to StackOverflow. You've used the javascript formatter and tagged your question with pandas. Neither has anything to do with your question. Show what you have tried so far (code) and be specific about which part is giving you trouble. Read: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – aneroid May 06 '21 at 23:40
  • Most straight-forward way: `[x for x in input_list for _ in range(n)]` where `n` is the number of times you want something to repeat, (in this case, `n == 2`) – juanpa.arrivillaga May 07 '21 at 00:11

2 Answers2

1

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])
Utsav
  • 5,572
  • 2
  • 29
  • 43
0

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]
Joffan
  • 1,485
  • 1
  • 13
  • 18