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 Sequences Sequence Iteration Iterating over Ranges

Jorge Grajeda
Jorge Grajeda
1,240 Points

I've struggled on this problem for a while

It keeps saying Val not defined or something, I've reviewed the videos a couple times and still couldn't think of anything or maybe there's something I'm not completely understanding.

iterating_ranges.py
my_list = []
for i in my_list.append(val):
    print(i)

1 Answer

Hi Jorge!

This passes:

my_list = []
for i in range(10):
    my_list.append(i)

range(10) creates your 0-9 set of values that the loop iterates over where each i is that iteration's value (0. 1, 2, 3, 4, etc., up to 9.)

By the way, range(10) goes 0-9

To go 0-10, you'd need range(11)

my_list.append(i) appends the value if each iteration's i variable to the my_list list

The range function is a very cool feature of python (shorthand code) that makes it easy to do that type of loop iteration.

Otherwise, you'd have to do something like:

my_list = []
my_range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in my_range:
     my_list.append(i)

Which would be kinda stupid (in this exact scenario), actually, because the end result would leave you with my_list and my_range being identical lists!?! LOL

More info:

https://www.w3schools.com/python/ref_func_range.asp

I hope that helps.

Stay safe and happy coding!

Bonus:

if you ran this:

my_list = []

for i in range(10):
     my_list.append(i)
     print(my_list)

or this:

my_list = []
my_range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in my_range:
     my_list.append(i)
     print(my_list)

your output would be the same:

[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]