[Tutor] How to print certain elements

eryksun eryksun at gmail.com
Tue Jan 21 12:33:02 CET 2014


On Tue, Jan 21, 2014 at 5:18 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> 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])] )

If you're using the `print` function, you can use the * operator to
unpack the items of the list. Add the option sep='\n' to print each
item on a separate line:

    items = [name for name in X if name not in (X[0],X[-1])]
    print(*items, sep='\n')

To get the `print` function in 2.x, add the following to the top of your module:

    from __future__ import print_function


More information about the Tutor mailing list