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

3
  • Iterate over the list items and append each item twice to a new list. Commented May 6, 2021 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. Commented May 6, 2021 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) Commented May 7, 2021 at 0:11

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.