"Pythonic" for looping over integers from 0 to k-1, except for i

I want to create a for loop that will go through integers from 0 to k-1, except for integer i. (I am comparing some lists of k elements, and I do not need to compare the element I in one list with the element I in another list.)

I have a pretty simple way to do this, but I keep thinking of a more “Pythonic”, elegant way to do this.

What am I doing:

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

It's easy enough, but one thing I like about Python is that it always seems like there is a smart one-line “Pythonic” trick for such things.

Thanks.

+6
source share
5 answers

Perhaps using itertools.chain

 from itertools import chain for j in chain(range(i), range(i+1, k)): # ... 
+11
source

I think I would do one of:

 for j in range(k): if j == i: continue ...code here... 

or (fixed)

 tocheck = range(k) for j in tocheck[:i] + tocheck[i + 1:]: ...code here... 

or

 for j in range(i) + range(i + 1, k): ...code here... 
+4
source

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

 i = 20 for j in range(50): if j==i: continue print j 
+4
source

How about this:

 for l in (j for j in range(k) if j != i): .... 

In this case, a generator expression is used, which can be considered "python", although the expression itself is a bit confusing, which can be considered inelegant.

+2
source

Another possibility is to simply use iterators:

 from itertools import chain k = 10 l = range(k) i = 2 print [el for el in iter(l[:i])] + [el for el in iter(l[i+1:])] 

This works for any list l . In the case of l just being some range , you can omit the explicit definition of l and simply write:

 print [el for el in xrange(i)] + [el for el in xrange(i+1,k)] 
+1
source

Source: https://habr.com/ru/post/974126/


All Articles