Skip to content Skip to sidebar Skip to footer

Is It Possible To Have A Python Inner 'for' To Continue Where The Outer For Stopped?

For exemple, say i have the following code: a = [[1],[2],[3]] for c in a: print(c) for d in a: print(d) The current output of it is: [1] [1] [2] [3] [2] [1] [2]

Solution 1:

I'd use the range and iterate over indexes:

a = [[1],[2],[3]]for c in range(len(a)): 
    for d in range(c, len(a)): 
        print(a[d])

Solution 2:

You can use enumerate and list slicing syntax (items[start:end:step], where start defaults to 0, end to items.length, and step to 1) to accomplish this:

items = [[1], [2], [3]]for i, _ in enumerate(items):
    for item in items[i:]:
        print(item)

Another interesting (though less efficient) option would be to use itertools.accumulate in conjunction with sum:

from itertools import accumulate

items = [[1], [2], [3]]for item in sum(accumulate(([x] for x in items[::-1])), [])[::-1]:
     print(item)

Solution 3:

You could use a list_iterator and branch off shallow copies as needed:

import copy
ia = iter(a)
for ai in ia:
    print(ai)
    for ai in copy.copy(ia):
        print(ai)

# [1]# [2]# [3]# [2]# [3]# [3]

Post a Comment for "Is It Possible To Have A Python Inner 'for' To Continue Where The Outer For Stopped?"