simple problem with lists I am just forgetting

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alexnb

    simple problem with lists I am just forgetting


    Lets say we have this list:

    funlist = ['a', 'b', 'c']

    and lets say I do this:

    if funlist[4]:
    print funlist[4]

    I will get the exception "list index out of range"

    How can I test if the list item is empty without getting that exception?
    --
    View this message in context: http://www.nabble.com/simple-problem...p18762181.html
    Sent from the Python - python-list mailing list archive at Nabble.com.

  • bearophileHUGS@lycos.com

    #2
    Re: simple problem with lists I am just forgetting

    Alexnb:
    How can I test if the list item is empty without getting that exception?
    In Python such list cell isn't empty, it's absent. So you can use
    len(somelist) to see how much long the list is before accessing its
    items. Often you can iterate on the list with a for, so you don't need
    to care of the len().

    Bye,
    bearophile

    Comment

    • Paul McGuire

      #3
      Re: simple problem with lists I am just forgetting

      On Jul 31, 2:51 pm, Alexnb <alexnbr...@gma il.comwrote:
      Lets say we have this list:
      >
      funlist = ['a', 'b', 'c']
      >
      and lets say I do this:
      >
      if funlist[4]:
          print funlist[4]
      >
      I will get the exception "list index out of range"
      >
      How can I test if the list item is empty without getting that exception?
      Try using a slice. Slices are ignorant of list index validity.

      funlist = list("abc") # too lazy to type ['a', 'b', 'c']
      if funlist[4:]:
      print funlist[4]

      Voila! No exception!

      -- Paul

      Comment

      Working...