Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a list repeating each element in Python

I'm using Python to infinitely iterate over a list, repeating each element in the list a number of times. For example given the list:

l = [1, 2, 3, 4]

I would like to output each element two times and then repeat the cycle:

1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... 

I've got an idea of where to start:

def cycle(iterable):
  if not hasattr(cycle, 'state'):
    cycle.state = itertools.cycle(iterable)
  return cycle.next()

 >>> l = [1, 2, 3, 4]
 >>> cycle(l)
 1
 >>> cycle(l)
 2
 >>> cycle(l)
 3
 >>> cycle(l)
 4
 >>> cycle(l)
 1

But how would I repeat each element?

Edit

To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - I would really like to repeat each element n times.

Update

Will your solution lead me to what I was looking for:

>>> import itertools
>>> def ncycle(iterable, n):
...   for item in itertools.cycle(iterable):
...     for i in range(n):
...       yield item
>>> a = ncycle([1,2], 2)
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2

Thanks for the quick answers!

like image 643
jb. Avatar asked Dec 20 '08 18:12

jb.


People also ask

How do you repeat a list of elements in Python?

The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).

Can you loop a list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


2 Answers

How about this:

import itertools

def bicycle(iterable, repeat=1):
    for item in itertools.cycle(iterable):
        for _ in xrange(repeat):
            yield item

c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]

EDIT: incorporated bishanty's repeat count parameter and Adam Rosenfield's list comprehension.

like image 133
Will Harris Avatar answered Sep 24 '22 02:09

Will Harris


You could do it with a generator pretty easily:

def cycle(iterable):
    while True:
        for item in iterable:
            yield item
            yield item

x=[1,2,3]
c=cycle(x)

print [c.next() for i in range(10)]  // prints out [1,1,2,2,3,3,1,1,2,2]
like image 41
Adam Rosenfield Avatar answered Sep 23 '22 02:09

Adam Rosenfield