Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Introducing Lists Using Lists Continental

How do you refer to a string in a list and then only print it if it starts with "A"

I tried alerting the list - not acceptable I tried adding an if statement before (and then after) the for statement - but was told couldn't access string.

The hint says "you can access characters in the string"

Thanks!

continents.py
continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]

for continent in continents:
    print("* " + continent)

3 Answers

Did you do continent(0) or continent[0]? if continent[0] == "A": print("* " + continent) should work

ah! Thank you. I was conflating syntax from JS with Python ... I definitely used () not []. Was thinking [] was only for indexing lists, and () was for indexing strings.

Thank you for catching that and pointing it out

The hint says "you can access characters in a string by index"

continent[0] would be the first character in continent.

Your idea of using an if statement is a good one.

ah, should've been "I tried altering the list"

How do I reference the items in the list if not through the for statement - I thought in "for continent in continents" the continent would act as a variable for each item in the list consecutively, and therefore I could write: if continent(0) == "A" print("* " + continent) this does not work - the error that time was that Asia did not appear in list ...

if "A" in continent: had the now obvious effect of printing any of the list items that have "A" anywhere in them (which included North America) but did tell me I can reference the items through the local(?) variable 'continent'

Finally ... pretty sure this is not how I was intended to do this (would be delighted to hear a less convoluted way if there is one):

if continent is < "B":