Python Python Sequences Sequence Iteration Iterating over Ranges

Jorge Grajeda
Jorge Grajeda
898 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

Peter Vann
MOD
Peter Vann
Treehouse Moderator 31,785 Points

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]