Bart Friederichs Bart Friederichs - 2 months ago 7
Python Question

Pythonic way to find integer in list of strings

I have an array as follows:

hour = ['01','02','12']


and I want

h = 1
str(h) in hour


to return
True
. What would be the most "Pythonic" way to do this? I could of course pad
h
with a zero, but is there a better way?

MMN MMN
Answer

A good rule of thumb is that the type and structure of data should reflect the model you have in mind. So, if your model is that hours are integers in the range 1..24, or whatever, you should model them that way:

hours = [ int(hr) for hr in hour ]

then things like:

h in hours 

become clean and obvious.