Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Boolean return if arbitrary element is in arbitrary list

Noob wondering how to improve his code.

a, b, c = string.split(enteredDate, "/")

m31s = [1, 3, 5, 7, 8, 10, 12]
m30s = [4, 6, 9, 11]

for x in range(len(m31s)):
    x = int(m31s[x])
    if x != int(a) and b != 31:
         print "Invalid date."
for x in range(len(m30s)):
    et cetera...

In case it isn't clear, I am testing an inputted date to see if it is valid. This is only part of the program. The main question is: what is the best way to test if an element matches ANY element in a list?

My method works... But, I suspect there is a better way to do this. I said boolean in the title because I envision something like:

if secretCode(m31s, int(a)) == True:

Could be a pipedream. Just curious.

Thanks to anyone who takes the time to help.

like image 675
d0rmLife Avatar asked Dec 05 '25 20:12

d0rmLife


2 Answers

You can use the syntax if elem in list. For example:

>>> if 1 in [1,2,3,4,5]:
...     print 'found 1'
... 
found 1
like image 176
Matthew Adams Avatar answered Dec 08 '25 10:12

Matthew Adams


You should use python datetime library.

try:
    datetime.datetime.strptime(enteredDate, "%m/%d/%Y")
except:
    print 'Invalid date'
like image 41
Dani Avatar answered Dec 08 '25 09:12

Dani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!