On 21/01/2014 10:24, Mkhanyisi Madlavana wrote:
How would I print washington and monroe using   [:]?
print X[::3]
How would I print every element but those two names?
print X[1::2]


On 21 January 2014 12:18, Alan Gauld <alan.ga...@btinternet.com
<mailto:alan.ga...@btinternet.com>> wrote:

    On 21/01/14 06:18, Adriansanchez wrote:

        Hello everyone,
        I am newbie to Python and programming in general. My question
        is, given a list:
        X=['washington','adams','__jefferson','madison','monroe']
        And a string:
        Y='washington,adams,jefferson,__madison,monroe'

        How would I print washington and monroe using   [:]?
        How would I print every element but those two names?


    The [:] syntax is used for selecting a range of values
    from a starting point to a finish.  Its not appropriate
    for selecting arbitrary items out of the list.

    If you know which items you want you can use a simple
    index to access them (remember the first item is index 0)

    So to print the first item and the fourth item:

    print(X[0],X[3])

    In your case it's the first and last so we can do
    a similar thing:

    print(X[0], X[4])

    But for the last element we can alternatively use
    a shortcut to save counting the indexes; that's use
    an index of -1:

    print(X[0],X[-1])

    Printing every element except those two is harder.
    The simplest approach is to use a loop to process
    the list and test each value:

    for name in X:
         if name not in (X[0], X[-1]):
            print name

    For the special case of excluding the first and
    last names you could use the [:] notation like
    this:

    print X[1:-1]

    But that only works where you want *all* the
    names in a sequence between two end points.

    Finally there is a more advanced way of filtering
    out items from a list called a list comprehension:

    print ( [name for name in X if name not in (X[0],X[-1])] )

    Which is pretty much our 'for' loop above, written in
    a shorthand single line form.

    hth


If you must top post please get your facts right.

In [1]: X=['washington','adams','jefferson','madison','monroe']

In [2]: print(X[::3])
['washington', 'madison']

In [3]: print(X[1::2])
['adams', 'madison']

--
My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to