The correct way to repeat twice in a list?

What is the correct way to do multiple iterations over a container? From the python documentation:

An iterator - a container object (for example, a list) creates a new iterator each time you pass it to the iter () function or use it in for a loop. Trying this with an iterator will simply return the same exhausted iterator object used in the previous iteration pass, making it look like an empty container.

The purpose of the protocol is that as soon as the iterators next () method calls StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are considered violated. (This restriction was added in Python 2.3; in Python 2.2, various iterators are violated according to this rule.)

If I have this code:

slist = [1,2,3,4]
rlist = reversed(slist)
list(rlist)
#[4,3,2,1]
tuple(rlist)
#()

What would be the easiest and most correct way to repeat the rlist twice?

+5
source share
4 answers
rlist = list(reversed(slist))

Then repeat as often as you want. This trick is applied more generally; whenever you need to iterate over an iterator many times, turn it into a list. Here is a snippet of code that I copy to different projects for this purpose:

def tosequence(it):
    """Turn iterable into a sequence, avoiding a copy if possible."""
    if not isinstance(it, collections.Sequence):
        it = list(it)
    return it

( Sequence- An abstract type of lists, tuples, and many custom objects like lists.)

+7
source

I would not save the list twice, if you cannot combine it to repeat once, then I would

slist = [1,2,3,4]
for element in reversed(slist):
    print element  # do first iteration stuff
for element in reversed(slist):
    print element  # do second iteration stuff

() . . , - , .

+5

?

. .

"rlist" ?

, , , , rlist "".

,

list(slist) # another copy of the list
tuple(slist) # still works!

, - , , :

rlist = list(reversed(slist)) # we store the result of the first iteration
# and then that result can be iterated over multiple times.

, itertools.tee. , , , . .

+3
source

Why don't you just flip the original list in place ( slist.reverse()), and then iterate over it as many times as you want, and finally undo it again to get the original list again?

If this does not work for you, the best solution to iterate through the list in reverse order is to create a new reverse iterator every time you need to iterate

for _ in xrange(as_many_times_as_i_wish_to_iterate_this_list_in_reverse_order):
    for x in reversed(slist):
        do_stuff(x)
+1
source

All Articles