Question regarding exercise: Passing a range into a function


#1


https://www.codecademy.com/courses/python-beginner-nzzVa/3/3?curriculum_id=4f89dab3d788890003000096


Hello. I completed the exercise, but did not quite understand why it worked. My question is the following: How can I recieve the correct answer in the interpreter when there is no list defined? So I added the range for which the function below would give me the answer and it gave me the right answer without having a list with elements defined. What confuses me also is the fact that the function in which I have declared the range is constructed to multiply it's elements by 2, despite this fact I manage to get the right answer. Thank you in advance.

My expectation for this exercise was either to recreate the function below to print the elements corresponding to the index range asked for or to simply create a new list with elements i.e. 0, 1, 2, 3, 4 and just print that list with a defined range, completely bypassing the use of the function.


'def my_function(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x

print my_function(range(0,3)) # Add your range between the parentheses!'


#2

The range function returns a list, so since you call range twice you've got two lists in your program


#3

But what list? There is no defined list. How can I get the elements in the console when they are not defined?


#4

range creates a list to return. That's its whole purpose.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.