Beginners question.

Discussion in 'Python' started by Player, Aug 31, 2004.

  1. Player

    Player Guest

    Hi all

    I am teaching myself python and so am following a few tutorials from

    In one of the tutorials an exercise is the following...

    As an exercise, write a loop that traverses the previous list and prints
    the length of each element.

    Firstly I just wanted to see if I could get the length out of those elements
    that were list type.
    I no thats not exactly what the exercise asks for, but I thought I would
    start there.
    However I am stuck and cant figure out why my code is doing what it's doing.
    My code is as follows....

    mylist = [1, 2, ["three", "four"], "five"]
    for item in mylist:
    if item == type(list):
    myitem = len(item)
    print myitem
    print item

    All my code seems to do is print out each element of the list on a new line.
    What I had expected it to do was this....

    but it doesn't, what it does do is this...

    ['three', 'four']

    I expected the line,
    myitem = len(item)
    to issue the variable, myitem, with a value that was the length of item.
    But as you cans ee it doesn't and simply ignores all that code and does the
    print item
    part instead, misisng out the first half of the for loop.

    Were am I going wrong ??

    Thanks in advance for any help :)

    M.B aka - Player -

    The Imagination may be compared to Adam's dream-
    he awoke and found it truth.
    John Keats.
    Player, Aug 31, 2004
    1. Advertisements

  2. Player

    Russell Blau Guest

    elements > that were list type.
    The "if" statement above is always false (well, at least for any list you
    are likely to encounter in real life), because you are looking to see if the
    item is equal to "type(list)" which is a type object. I think you meant:

    if type(item) == list:

    That's why your len() statement was never being reached.
    Russell Blau, Aug 31, 2004
    1. Advertisements

  3. General tip: Don't forget how much fun the interpreter is:

    Python 2.3.4 (#1, Jun 8 2004, 17:41:43)
    [GCC 3.3.3 20040217 (Gentoo Linux 3.3.3, propolice-3.3-7)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    Jeremy Bowers, Aug 31, 2004
  4. Player

    Player Guest


    Ok thanks Russell Blau :) I can see it now heh.

    M.B -aka- Player
    Player, Aug 31, 2004
  5. It's very unlikely that the item will equal the type of list (which is
    the builtin metaclass 'type' itself). You presumably mean:

    if isinstance(item, list):

    Alex Martelli, Sep 1, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.