Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to have nested for-loops indexes that don't start from 0?

So one issue I discovered with python is that it is not very user-friendly to create nested loops each with their own indexes.

How would I write the Python-equivalent of this Java code:

for(int i = 0; i < array.length-2; i++){
    for(int j = i+1; j < array.length-1; j++){ 
       for(int k = j+1; k < array.length; k++){

Notice how I reference the counter value of the predecessor's for each nested loop. I tried using:

for idx, val in enumerate(nums[:-2]):

but it seems like idx will always start at 0 rather than start at the predecessor's index value. Is there a better solution besides maintaining separate counter variables?

like image 756
btrballin Avatar asked Dec 18 '22 02:12

btrballin


2 Answers

From [Python.Docs]: Built-in Functions - enumerate(iterable, start=0) (emphasis is mine):

The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

Example:

num = [0, 2, 4, 6, 8]
start = 2
for idx, val in enumerate(num[start:], start=start):
    print("Index: {0:d}, Element: {1:d}".format(idx, val))

Output:

Index: 2, Element: 4
Index: 3, Element: 6
Index: 4, Element: 8
like image 152
CristiFati Avatar answered Dec 27 '22 02:12

CristiFati


It's very simple to do that using range or xrange. Here's how you do it.

Java version:

for(int i = 0; i < array.length-2; i++) {
    for(int j = i+1; j < array.length-1; j++) { 
        for(int k = j+1; k < array.length; k++) {

Python version:

for i in xrange(0,len(arr)-2):
    for j in xrange(i+1, len(arr)-1):
       for k in xrange(j+1, len(arr)):

I hope that helps!

like image 37
Sourav Badami Avatar answered Dec 27 '22 00:12

Sourav Badami