Home > Enterprise >  How to iterate the first index value twice before going to the next index position?
How to iterate the first index value twice before going to the next index position?

Time:05-24

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?

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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.

CodePudding user response:

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.)

CodePudding user response:

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

for x in l:
   for i in range(2):
      lst  = [x]
print(lst)
# [1, 1, 2, 2, 3, 3]
  • Related