If list exists Python
Ngày đăng:
06/01/2022
Trả lời:
0
Lượt xem:
71
Check if Index Exists in Python ListPython Python List Created: October-19, 2021 | Updated: December-25, 2021 Show We will introduce two methods to check if a list index exists using the list range and the IndexError exception. Check if Index Exists in Python List Using the List RangeWe will have to check if the index exists in the range of 0 and the length of the list. Output: Index 0 in range Index 1 in range Index 2 in range Index 3 not in range Index 4 not in rangeCheck if Index Exists in Python List Using The IndexErrorWhen we try to access an index that does not exist in a list, it will raise an IndexError exception. fruit_list = ['Apple','Banana','Pineapple'] for index in range(0,5): try: fruit_list[index] print("Index ",index," in range") except IndexError: print("Index ",index," does not exist") Index 0 in range Index 1 in range Index 2 in range Index 3 does not exist Index 4 does not existContribute DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page. Related Article - Python List
|