1

Tried a search but couldn't locate anything. I'm looking for the simplest to replace

if myList and len(myList)>4

with something shorter:

myList = [1,2,3,4,5]

if myList and len(myList)>4: 
    print myList[4], len(myList)

since

if not myList[4]

doesn't do job.

7
  • if len(myList) > 4: is shorter (and equivalent as long as myList is actually a list) ... Commented Apr 11, 2014 at 5:21
  • Normally you could just do if len(myList) > 4. If you need the if myList, it's probbaly because of something else you're not showing here. Commented Apr 11, 2014 at 5:22
  • myList can arrive as None. I need to check that first... Commented Apr 11, 2014 at 5:22
  • @Sputnix be explicit then. if myList is not None and len(myList)> 4: Frankly I'd test for None-ness first and handle that case separately than just if len(myList) <= 4 Commented Apr 11, 2014 at 5:24
  • if not myList Falses on an empty list too which works in my situation well. But thanks! Commented Apr 11, 2014 at 5:25

3 Answers 3

4

Not really sure what's being asked, but I'll hazard a guess that EAFP is the right concept here.

try:
    myList[4]
except IndexError:
    # handle it

Basically, try to do the thing you want to do with index 4. If you can't, and it's because of an IndexError, handle it the way you'd handle it if your if len(myList) > 4 failed.

Sign up to request clarification or add additional context in comments.

1 Comment

Good suggestion too. Wishing for shorter!
3

You can try extending the built-in type list and override __getitem__() to get your intended behavior.

class MyList(list):

    def __getitem__(self, index):
        try:
            return super(MyList, self).__getitem__(index)
        except IndexError:
            return None

mylist = MyList([1,2,3,4,5])
print mylist[4] #prints 5
print mylist[6] is None #prints True

Personally, I'd go for Adam Smith's suggestion.

1 Comment

I actually like yours! Thanks!
0

Try this,

>>> if len(myList)> 4 : print myList[4]

Update

>>> if len(myList)> 4 and isinstance(myList,list) : print myList[4]

4 Comments

len(None) throws TypeError: object of type 'NoneType' has no len()
well, in "a real life" there will be no way to anticipate what myList is.
Thanks! A check for None needs to proceed len() otherwise things get screwed really fast! :)
You should also use isinstance(myList,list) rather than type(myList) is list to preserve inheritance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.