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
  • 16,448
  • 3
  • 17
  • 42
Sebastian Nin
  • 162
  • 1
  • 11
  • 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
  • 123,782
  • 12
  • 99
  • 138
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
  • 84,957
  • 6
  • 91
  • 136
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
  • 15,040
  • 7
  • 22
  • 53
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
  • 9,559
  • 2
  • 24
  • 32