Python Introducing Lists Using Lists Continental

Markus Garmeister
Markus Garmeister
1,104 Points

How can I filter list elements by there first letter?

continents = [ 'Asia', 'South America', 'North America', 'Africa', 'Europe', 'Antarctica', 'Australia', ] n=0 while n <= len(continents) - 1: a_continent = continents[n] if a_continent[0] == "A": a_continents = a_continents.append(a_continent) else: print(a_continents)

continents.py
continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
n=0
while n <= len(continents) - 1:
    a_continent = continents[n]
    if a_continent[0] == "A":
        a_continents = a_continents.append(a_continent)
else:
    print(a_continents)

1 Answer

Reuben Rushton-Taylor
Reuben Rushton-Taylor
2,721 Points

First of all, you will need to define a_continents as a list, as it is not defined.

Within your if statement, you only need a_continents.append, as the .append will assign the continent to the list.

You should also increment 'n' as you go, otherwise the while loop will loop forever.

Example:

continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
a_continents = [] #defining a_continents
n=0
print(len(continents))
while n <= (len(continents) - 1):
    a_continent = continents[n]
    n +=1 #incrementing n
    if a_continent[0] == "A":
        a_continents.append(a_continent) #appending a list
else:
    print(a_continents)

alternatively swap out with a for loop:

for x in continents:
    if x[0] == "A":
        a_continents.append(x)
print(a_continents)
Louise St. Germain
Louise St. Germain
Treehouse Moderator 15,554 Points

Hi Reuben,

I just changed this to an answer so others can see it, and so it has a chance to get upvoted/selected as best answer!