[Tutor] List Python Question..Please help

Steven D'Aprano steve at pearwood.info
Sat Sep 28 05:15:00 CEST 2013


On Fri, Sep 27, 2013 at 12:04:38PM -0500, Jacqueline Canales wrote:
> composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
> x = 'Antheil'
> s = 'Saint-Saens'
> h = 'Beethoven'
> y = 'Easdale'
> k = 'Nielsen'

This is a step backwards from what you had in your first post. You had 
the right idea in the first case:

for name in composers:
    ...

Then you just write a bit of code that checks `name`, rather than a bit 
of code to check `x`, another bit of code to check `s`, a third bit of 
code to check `h`, a fourth to check `y`, ...  What if you had ten 
thousand names to check? A for-loop doesn't care if there's one name or 
ten thousand names, computers are really good at that sort of tedius 
grunt-work. 

So, go back to where you started:

for name in composers:
    # check whether name starts and ends with the same letter


You want an "if" test. In English:

    if first letter of name equals last letter of name:
        print name


How do you get the first letter of name? 

name[0]


How do you get the last letter of name?

name[-1]


How do you test if two things are equal?

# replace x and y with the first and last letter of name, as above
x == y  

is *almost* right. It's not quite what you want, because it is 
case-sensitive. 'A' == 'a' will return False, since they are not 
precisely them same. You need to make them the same case:

x.lower() == y.lower()  # or upper() if you prefer


Putting it all together:


for name in composers:
    if **** == **** :
        print name


where you have to replace the stars **** with:

first letter of name, converted to lower/upper case

last letter of name, converted to lower/upper case


respectively.



-- 
Steven


More information about the Tutor mailing list