When you expect that a sequence will only have one item, and are only interested in the first it is common to grab the zeroth element. This will fail if the sequence is unexpectedly empty, but you might unintentionally silently throw away extra elements:
>>> a = 'a'[0]
>>> a = ''[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> a = 'ab'[0] # oops, silently dropped b
An alternative idiom is to use sequence unpacking with a single item. This way neither unexpected condition will silently pass.
>>> a, = 'a'
>>> a, = ''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> a, = 'ab'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
thank you.
ReplyDelete
ReplyDeleteThanks for the sharing the post
python training institute in south delhi
python training institute in noida
I appreciate your post. Thanks for sharing
ReplyDeletePython course in delhi
Python course in noida
your blog was really interesting,I have learnt so much.
ReplyDeletepython training institute in south delhi
python training institute in noida
ReplyDeletesuch an interesting post shared by you
Python course in Delhi
Python course in Noida
Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. 안전놀이터
ReplyDeleteThis is an excellent article. I recently discovered your blog and have quite liked reading your writings. I'm looking for the best essay website where I may learn more useful information. Thank you very much for the excellent information.
ReplyDelete