Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Using Lists Continental

Markus Garmeister
Markus Garmeister
1,465 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

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
19,424 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!