LA_
LA_

Reputation: 20409

How to check presence of the element with particular index in the list?

I extract the data received from 3rd party server:

data = json.loads(response)
if data:
    result = data.get('result')
    if result and len(result)>=38 and len(result[38])>=2: 
        for item in result[38][2]:
        ...

The idea of the condition is to check if the list contains element with index 38 (result[38]) and subelement with index 2 (result[38][2]), but looks like it doesn't work since I get the following exceptions -

if result and len(result)>=38 and len(result[38])>=2:

TypeError: object of type 'NoneType' has no len()

or

for item in result[38][2]:

TypeError: 'NoneType' object is not iterable

How should I modify my condition?

Upvotes: 0

Views: 97

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Your result[38] value is None, and len(result[38]) fails because the None singleton has no length. Even if it was not None, your test could also fail because you need 39 elements for index 38 to exist, but you only test if there are at least 38 elements. If there are exactly 38 elements, your len(result) >= 38 test would be true but you'd still get an IndexError.

Use exception handling, rather than testing every element:

data = json.loads(response)
try:
    for item in data['result'][38][2]:
        # ...
except (KeyError, TypeError, IndexError):
    # either no `result` key, no such index, or a value is None
    pass

This is far simpler than testing all the intervening elements:

if result and len(result) > 38 and result[38] and len(result[38]) > 2:

Upvotes: 2

Related Questions