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

Jorge Grajeda
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jorge Grajeda
Python Development Techdegree Graduate 8,186 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]