简体   繁体   中英

To check whether index of list exists

Is there any solution to check whether index of list exists?

Other than:

  1. using len(list)

  2. using

     try: ... except IndexError: ... 

As dict has a dict.has_key(key) to check whether key exists, is there any method to check index for list?

No, there are no additional methods to test if an index exists.

Dictionary keys are not easily predicted; you have to have a membership test to determine if a key exists efficiently, as scanning through all keys would be inefficient.

Lists do not suffer from that problem; len(somelist) is cheap (the length is cached on the list object), so index < len(somelist) is the way to test if an index exists, with exception handling a great fallback if you expect the index to be within the list boundaries most of the time.

You could use list comprehensions.

index in [someList.index(item) for item in someList]:

This will return true if there are at least index items in the list.

For dictionaries you could do something similar:

index in [someDictionary.keys().index(item) for item in someDictionary.keys()]

It's worth pointing out that this really is a moot point since using len(list) or try ... except works perfectly well. But hey, you asked for another way, so here's another way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM