0

I'm trying to make a for loop that iterates each index twice before going to the next one, for example if I have the following list:

l = [1,2,3]

I would like to iterate it if it was in this way:

l = [1,1,2,2,3,3]

could someone help me with this problem please?

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
Sebastian Nin
  • 184
  • 1
  • 13
  • 2
    Does this answer your question? [Repeating elements of a list n times](https://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times) – Ynjxsjmh May 23 '22 at 16:41
  • @Ynjxsjmh That's explicitly about creating a new list, while this one is about iterating and thus allows other solutions (like the currently top-voted generator solution). – Kelly Bundy May 23 '22 at 17:03

5 Answers5

4

The most obvious thing would be a generator function that yields each item in the iterable twice:

def twice(arr):
   for val in arr:
       yield val
       yield val

for x in twice([1, 2, 3]):
    print(x)

If you need a list, then

l = list(twice([1, 2, 3]))
AKX
  • 152,115
  • 15
  • 115
  • 172
3

You could make a list comprehension that repeats the elements and flattens the result:

l = [1,2,3]
repeat = 2

[n for i in l for n in [i]*repeat]
# [1, 1, 2, 2, 3, 3]
Mark
  • 90,562
  • 7
  • 108
  • 148
2

You can solve this by using NumPy.

import numpy as np

l = np.repeat([1,2,3],2)

Repeat repeats elements of an array the specified number of times. This also returns a NumPy array. This can be converted back to a list if you wish with list(l). However, NumPy arrays act similar to lists so most of the time you don't need to change anything.

2

Unsurprisingly, more-itertools has that:

>>> from more_itertools import repeat_each
>>> for x in repeat_each([1, 2, 3]):
...     print(x)
... 
1
1
2
2
3
3

(It also has an optional second parameter for telling it how often to repeat each. For example repeat_each([1, 2, 3], 5). Default is 2.)

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
1
l = [1, 2, 3]
lst = []

for x in l:
   for i in range(2):
      lst.append(x)
print(lst)
# [1, 1, 2, 2, 3, 3]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47