Python question () []

Discussion in 'Mac Programming' started by larswik, Mar 7, 2009.

  1. larswik macrumors 68000

    Sep 8, 2006
    Hello again, Learning Python still. I came across part of the book and I can't remember reading about putting things in parenthesis and brackets. Now it is starting to show up in the tutorials and I don't want to move forward till I understand them.

    Example #1 ()

    while (guess != the_number):
    #Can I not write that saw code like this bellow?

    while guess != the_number:

    Example #2 []

    word = "index"
    print word [1]

    # the result would be n when I use it with the 'len'. why is the number surrounded by a bracket? can I write the same code like this and get the same results?

    word = "index"
    print word 1


  2. eddietr macrumors 6502a

    Oct 29, 2006
    Yes, you can omit the parens in this case in python. You may choose to include them (at your option) if you think it makes the program easier to read and understand. In this case, I would probably omit them myself since it add very little to the readability of the code.

    So this is a different concept all together. Lists are a very basic and common concept in Python. Lists are basically a sequence of items.

    And to reference a particular item in that list, you use the [] operator. And of course like most other languages, you start counting the items with 0. So the 3rd item of some list is found with theList[2]. The fourth item is at theList[3] and so on.

    Strings in Python can basically be treated as lists. So if you have a string "index", it is as if you have a list of 5 characters. And so if that string "index" is called "word", then word[1] will give you the 'n' in index.

    The point being that [n] is the operator that gives you a particular item in a list. And strings can be manipulated as if they were lists.

    I would definitely recommend the Python tutorial for a lot more good stuff about lists. If you want to learn Python, I would say lists are the most important concept of all.
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    In regard to the while, here are the applicable pages from the python documentation:
    Re: the while statement

    while_stmt ::= "while" expression ":" suite
    ["else" ":" suite]

    So any expression can go after the while.

    Parenthesized forms:

    A single expression within parentheses is equivalent to the expression without parentheses. You would be fine doing something like:
    while (((((x == y))))) :
    It would be the same as including no parentheses.

    Regarding [], see the sub-section labelled Sequences in this section:

    eddietr did a good job of describing these, I wasn't posting because of any failure there, I just think it's good when you're starting out to be able to seek out, read, and understand documentation.


Share This Page