Python Introducing Lists Using Lists Continental

Sarah Burgart
Sarah Burgart
2,368 Points

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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 43,344 Points

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

Sarah Burgart
Sarah Burgart
2,368 Points

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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 43,344 Points

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.

Sarah Burgart
Sarah Burgart
2,368 Points

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":