Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Pythonic" for loop over integers 0 to k-1 except i

I want to create a for loop that will go through the integers 0 to k-1, except for integer i. (I'm comparing some lists of k items, and I don't need to compare item i in one list with item i in another list.)

I have a fairly easy way to do it, but I keep thinking there's a more "Pythonic", elegant way to do it.

What I'm doing is:

tocheck = range(k)
del(tocheck[i])
for j in tocheck:

It's easy enough, but one thing I like about Python is that it seems like there's always a clever one-line "Pythonic" trick for things like this.

Thanks.

like image 343
Alex Small Avatar asked Aug 20 '14 21:08

Alex Small


2 Answers

Perhaps using itertools.chain

from itertools import chain

for j in chain(range(i), range(i+1, k)):
    # ...
like image 82
FatalError Avatar answered Oct 06 '22 18:10

FatalError


I think the most idiomatic way to leave a gap would be to skip in the for loop using continue.

i = 20
for j in range(50):
    if j==i:
        continue
    print j
like image 41
Andrew Johnson Avatar answered Oct 06 '22 18:10

Andrew Johnson