3

I have the following code:

def get_preds(train,test,x_ranges,y_ranges):
    global total_scores
    global num_scores
    for x_min, x_max in x_ranges:
       for y_min, y_max in y_ranges:
           ...

When I run this method on python 2.7, it behaves as expected. The nest for loops runs for each time that the outer for loop runs.

When I loaded this same code onto the Kaggle python script engine which runs on Python 3, the nested loop only runs once. For all other iterations, it is skipped.

Here's how the method gets called:

dataset = pd.read_csv('../input/train.csv',dtype=types,index_col=0)
split_t=math.floor((0.9)*786239)

train = dataset[dataset.time < split_t]
test = dataset[dataset.time >= split_t]


def gen_ranges(size,step):
    return zip(np.arange(0,size,step), np.arange(step, size+step, step));

x_ranges = gen_ranges(size,x_step)
y_ranges = gen_ranges(size,y_step)

preds_test_total = get_preds(train,test,x_ranges,y_ranges)
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
Larry Freeman
  • 418
  • 6
  • 19
  • 1
    how do you call the function? – Tadhg McDonald-Jensen May 30 '16 at 19:53
  • preds_test_total = get_preds(train,test,x_ranges,y_ranges) outside of any method. – Larry Freeman May 30 '16 at 19:56
  • 1
    how do you call the function? in particular, `yranges` is a list in both interpreters or it is a list in Python 2 and a generator in Python 3? – gboffi May 30 '16 at 19:57
  • That doesn't really give me any information, what is `x_ranges` and `y_ranges`? are they the result of the `zip` or `map` or one of the other functions that were changed in python 3 that return an iterator instead of a list? – Tadhg McDonald-Jensen May 30 '16 at 19:58
  • I updated the question with the code that calls the function. – Larry Freeman May 30 '16 at 19:59
  • 3
    Yep, zip returns an iterator in python 3 instead of a list in python 2, which means this is a duplicate of [Performing len on list of a zip object clears zip](http://stackoverflow.com/questions/14637154/performing-len-on-list-of-a-zip-object-clears-zip) – Tadhg McDonald-Jensen May 30 '16 at 20:00
  • Thanks, Tadhg McDonald-Jensen! I'm still learning Python 3 so this is very good to know! – Larry Freeman May 30 '16 at 20:07
  • 1
    Larry, imho you should delete the full function listing and, maybe, also the indentation remark. Should you follow this advice, your question would be much easier to read and more likely to be upvoted (at least by me...), – gboffi May 30 '16 at 20:45
  • @gboffi, I like your suggestion. I've made the changes. – Larry Freeman May 30 '16 at 20:47

1 Answers1

2

In Python 3, zip() returns an iterator. You can only iterate through the elements of an iterator once. To replicate the Python 2 behavior, use list(zip(...)) in place of zip(...).

augurar
  • 12,081
  • 6
  • 50
  • 65