[Tutor] How to print certain elements

Alan Gauld alan.gauld at btinternet.com
Tue Jan 21 11:18:49 CET 2014


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

Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list