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 Python Collections (2016, retired 2019) Lists Shopping List Take Three

Alternative for loop

Alternative loop statement:

for i in range(len(shopping_list)):
    print("{}. {}".format(i, shopping_list[i]))

Does this seem cleaner?

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I actually really like that and do think it looks a bit cleaner. That being said, it doesn't really function like the one in the video as it will start the numbering at 0. So assuming the first item in the shopping list is "bread", you will see output like:

0. bread

instead of...

1. bread

But that is easily fixed! You can actually include a + 1 inside the print statement to take care of that. Take a look:

print("{}. {}".format(i + 1 , shopping_list[i]))

But I dare say you could even make that a little cleaner, and it is supported in workspaces but likely will not be introduced until later down the line. It's called an "f string". You can get that same output with this line. Take a look:

print(f"{i+1}. {shopping_list[i]}")

I think that last line is about as concise as you're going to get it. Hope this helps and way to ask great questions! :sparkles:

edited for additional information

I don't really think you're at this stage yet, but you could also use the builtin function enumerate here. You could rewrite that for loop like so:

for index, value in enumerate(shopping_list, 1):
  print(f"{index}. {value}")

This takes every index and its corresponding value and prints them until it reaches the length of shopping_list. The 1 at the end of the arguments is the offset for the starting value of the index.