18/18.Using a list of list in function, how to use """for i in range(0,len())""" to achieve goal? Thx!


#1



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

Traceback (most recent call last):
File "python", line 10, in
File "python", line 6, in flatten
TypeError: range() integer end argument expected, got list.

I want to use """for i in range(0,len())""" instead of """for numbers in lists""" and """for number in numbers""" to achieve the goal.
it seems like i can't easily use """lists[i][j]""",and there might be something else wrong in the code.
how to achieve that?
thanks a lot!


Replace this line with your code. 
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    for i in range(0,len(lists)):
        for j in range(0,lists[i]):
            results.append(lists[i][j])
    return results
    
print flatten(n)


#2

This line has the mistake:

for j in range(0,lists[i]):

the range method expects both arguments to be integer. But the second argument (lists[i]) is not an integer but a list in itself (remember that each element of lists is a list itself). Hence the error.

To fix this, you can add the len method here - for j in range(0,len(lists[i])):

Btw, a shorter way to write your code would be:

for sub_list in lists:
    for elm in sub_list:
        results.append(elm)

since you don't care about the index, and all you need is the element itself, using range is extra effort.


#3

Thank you very much.
You answered my question. Problem comes from argument in range() should all be int.
What I exactly want to do is to consider the situation when I need to care about the index.


#4

Then you would need to use the range method. Also, have a look at the enumerate function :slight_smile:


#5

thank you again!
And you gave me a good learning website! :wink: