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 trialCaroline Louw
12,155 PointsI am trying to find out if A is in my list in python. What is wrong with my code?
How do I index a character in a string using a for loop?
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
# Your code here
for continents[0] in continents:
if "A" in continents:
print(continents)
4 Answers
Evaristus Okafor
1,405 PointsMaybe you want to loop through a list and print only the continents whose name starts with "A". Another way to do it is to use the equality operator, "==".
for continent in continents:
if continent[0] == "A":
print(continent)
But is some of the continents starts with lower case for "asia", You will not be able to get it because pything is case sensitive. so to be sure you get all the continents whose name starts with "A" or "a".
for continent in continents:
if continent[0].upper() == "A":
print(continent)
Jeff Muday
Treehouse Moderator 28,720 PointsYou seem to get the concept-- the syntax is a little different.
# continent is used as the current continent with looping through continents
for continent in continents:
if "A" in continent:
print(continent)
Jeff Muday
Treehouse Moderator 28,720 PointsOne of the things that I love about programming is there are many ways to get the same result. For example, some people like a solution that "reads" well (i.e. self documenting code).
for continent in continents:
if continent.startswith("A"):
print(continent)
Caroline Louw
12,155 PointsThank you guys. This helps
Jesus Reyes
1,946 PointsJesus Reyes
1,946 PointsIm deleting my answer, this is WAY better!!, it makes no sense to try find a match to a single character using
in
and also setting the character toupper
or evenlower
at the moment of comparison will make sure you get a match regardless of how is written on the list.