Nested for-loop in python with staggered start variable

Viewed 121

Here's a simple version of the code I'm trying to achieve:

for key, value in data.items():
    for key2, value2 in data.items():
        # other stuff

I'm looking for a way to start key2 off at key. So, for example in C++ it would be:

for(int i=0; i<n; i++){
    for(int j=i; j<n; j++){
       # other stuff
    }
}

I need to be able to go through the whole data set. key is a string and value is a list that isn't in any particular order so I can't just check if key2 < key.

2 Answers

You could do this with enumerate :

for i, (key, value) in enumerate(data.items()):
    for key2, value2 in list(data.items())[i:]:
        #stuff

If you want to iterate over all unordered pairs, a natural solution is using itertools.combinations. This has the added advantage of only requiring one level of indentation for the loop.

import itertools as it

for (k1, v1), (k2, v2) in it.combinations(data.items(), 2):
    ...

If you want to include pairs where k1 == k2, you can use combinations_with_replacement:

for (k1, v1), (k2, v2) in it.combinations_with_replacement(data.items(), 2):
    ...
Related