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 to iterate using for loop

What is another way to do the iteration using for loop?

continents.py
continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
for continent in continents:
    i=0
    while i<2:
        print("*"+continent[i])
# Your code here
nakalkucing
nakalkucing
12,964 Points

Hi Kushagra Shukla! I really like seeing other people's different coding solutions. (Yours is a neat one.) I look forward to seeing any other ways people post here! But, here's the unimaginative ;) way I did it:

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

2 Answers

nakalkucing That will print the entire list. What if i have to print only the first two elements of the list?

nakalkucing
nakalkucing
12,964 Points

Hmmm... I see. Sorry about that. Kicking myself for not paying enough attention. ;)

I'm now experimenting with the code to find a way to print off the first 2 elements of the list. :)

nakalkucing
nakalkucing
12,964 Points

Ok. After consulting a friend, we came up with this:

i=0
for continent in continents:
    if i < 2:
        print("* " + continent)
        i += 1
nakalkucing
nakalkucing
12,964 Points

Just being silly here, Kushagra Shukla. But, if you need the first two elements printed out in place of every other element of the list...

continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
for cont in continents:
    print ("* " + str(continents[0 : 2]))

Happy Coding! :)