Search code examples
pythonpython-3.xloopsfor-looppython-zip

zip loop not functioning as intended


I tried making a range based for loop using zip but it isn't selecting the entries of my list as expected. The code is as follows:

for lower, current, higher in zip(energy[:len(energy)-1], energy[1:len(energy)-1], energy[1:]):
      lowerE = round(findE(lower, current, tol),dec)
      higherE = round(findE(current, higher, tol),dec)
      print(str(lower) + " " + str(lowerE) + " " + str(current))
      print(str(current) + " " + str(higherE) + " " + str(higher))

where findE(min,max,tol) is an algorithm which searches zeros of numerically evalued functions between min and max with precision tol and dec is calculated from tol (currently tol is 1e-4 and dec 4).

Running the loop with start array energy = [0,0.5,2] I expect the output to be:
0 lowerE 0.5
0.5 higherE 2

where higherE and lowerE are whatever. What I'm getting instead is
0 lowerE 0.5
0.5 higherE 0.5\

what's wrong in my loop definition?


Solution

  • Your loop isn't zipping at three different offsets, it's just at two offsets. Eliminating the unnecessary elements of each slice (since zip stops when the shortest iterable is exhausted anyway), you're looping over zip(energy, energy[1:], energy[1:]), when you almost certainly intended to be looping over zip(energy, energy[1:], energy[2:]) (note the change from 1 to 2 in the final slice), so you got three adjacent values, not one value, followed by the next value repeated twice.