0

Let's suppose I have a list of 1000 values, however, I am not interested in values between 111 and 889. Is there a way in python to entirely skip iterations of a for loop without using continue to reduce time complexity? It seems like a waste to run the for loop 1000 times when I only need to run it 222 times.

l = [1,2,3,111,5,6,7,8,9,889,12,2,111,4,5,6,889]
for i in l:
    if i == 111:
        // skip to 889
    else:
        // do stuff

There could be multiple occurrences of 111 and 889 in this list and all the values in between should be skipped. If there is no 889 after 111 the for loop should end

OmO Walker
  • 611
  • 6
  • 13

3 Answers3

1

You can use a while loop.

idx = 0
while idx < 1000:
    if idx == 111:
        idx = 889
    else:
        # do stuff
        idx += 1

For your edited question, I'm afraid there is no better way than traversing the whole list by using continue since you don't know where the 889 appears in the list.

Erich
  • 1,838
  • 16
  • 20
1

You can create two slices of your iterable then chain them together to iterate through them:

import itertools as it

my_list = list(range(1000))
my_slice1 = it.islice(my_list, 0, 111)
my_slice2 = it.islice(my_list, 889, 1000)
new_iterable = it.chain(my_slice1, my_slice2)
for i in new_iterable:
    print(i)
Joshua Hall
  • 332
  • 4
  • 15
1

You changed the question totally in between, One thing you should notice that if you have unsorted list of length, no matter whatever you do, O(n) is the best case scenario.

If list has some pattern or derived from formula, or is periodic, there might exist some minor optimization.

You can optimize little bit by using libraries like numpy, you can get good optimization only in case your input array is also numpy array, else use itertools, filter etc if you are only going with list

# with numpy
import numpy
a = numpy.array([1,2,3,111,5,6,7,8,9,889,12,2,111,4,5,6,889])
filter_array = a[numpy.logical_or(a < 111, a >889)]

#with filter
l = [1,2,3,111,5,6,7,8,9,889,12,2,111,4,5,6,889]
filter_list_gen = filter(lambda x : x > 889 or x < 111, l)
for l in filter_list_gen:
    #  do the stuff
    pass
  • Numpy perfect for array manupulation, you will need to run loop, plus numpy filtering loop, but it will help you have many array manupulation overall

  • filter id just like normal iterating, but little faster, its like lazy eval.

Rushikesh
  • 129
  • 1
  • 4