min () expected sequence error only happens for newly created objects in edit mode

I wrote a script that selects the selected object's vertices with the lower Z value, and set's the origin of the object to the median point.
Everything worked perfectly until I tried to make things a bit better, by returning the 3D view mode to the mode that was used before running the script as in Edit Mode or Object Mode... etc.

The error I'm getting happens in a very specific case, and I couldn't find no logical explanation to it. I have "New Object in Edit Mode" enabled in my user preferences, so when I create a new object and run this scrip immediately, I'm getting an error:

 min() arg is an empty sequence

• This error only occurs when an new object is created in Edit Mode, then I run the script immediately.
• I tried disabling creating new object in Edit Mode, the error disappeared!
• Even if create new object in Edit Mode is enabled, the error wont occur if I press tab to go to Object Mode first, then tab again to go back to Edit Mode, then run the script.
• This error will not occur in any other cases whether run in Object Mode or Edit Mode.
• I tried saving right after creating a new object in Edit Mode, then run the script, no error!
This is a very weird situation to the programming novice me, so what am I doing wrong here? help appreciated in advance, blend file attached.
Edit: I found a solution by unchecking "create in edit mode" off in user preferences, then checking it back after applying the rest of the code in the example, but I want to understand why is this error happening.
• (Without having downloaded and checked file) You are passing an empty list to min(...) Either check for it, or use min(sequence, default=0) to return 0 when the list is empty. – batFINGER Dec 2 '16 at 5:16
• Nope, this didn't solve the problem, first I tried it as is, but I got an Error "Sequence undefined", then I put it in quotation 'sequence', so I'm back to square 1, same error @batFINGER – Georges Dec 4 '16 at 10:02
• It will need to be the name of the list (sequence) in the min function in your code. – batFINGER Dec 4 '16 at 13:18
• batFinger's comment could be the right answer, but as I explained I'm a programming noob, it didn't really provide me an answer, if I was a seasoned programmer, most probably I wouldn't be asking this question in the first place :) – Georges Dec 10 '16 at 19:07
• You need to update your edits if you are not using bmesh. Add these to lines first to your def: if bpy.context.object.mode == "EDIT": bpy.context.object.update_from_editmode() – JuhaW Dec 14 '16 at 14:24

if bpy.context.object.mode == "EDIT":