0

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]
[3]
[3]
[1]
[2]
[3]

My question is whether it is possible to modify this code in a pretty way so that the output becomes like this:

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

In other words if it is possible, in a 'clean python', to have the inner loop to cover the list from the index the outer loop stopped.

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.