18/18 the second way? help


#1
#function unites lists within a list, resulting in one long list      
def flatten(lists):
    #creating an empty list  
    results=[]
    #running through the outer list  
    for numbers in range(len(lists)):
        #running through the inner list
        for i in range(len(lists[numbers])):
            #appending each item to the results list    
            results.append(lists[numbers[i]])
    return results           

print flatten(n)

console:
Traceback (most recent call last):
File “python”, line 16, in
File “python”, line 13, in flatten
TypeError: ‘int’ object has no attribute ‘getitem


#2

here:

results.append(lists[numbers[i]])

numbers is a integer. you can’t access integers by index. Seems you use the wrong variable there

Why would you use range? range is useful when we want to update elements in a list, which we are not doing.

Here is the general syntax of what you want to do:

the_list[outer_index][inner_index]

you nested the square brackets wrong


#3

Hi’

thank you so much for your quick reply, it did the work.
I did it for practice reasons.


#4

but do you also understand why?


#5

I think so:
The index is an integer pointing to location of the list, not the list itself, and the syntax for getting to the nested list is list[outer][inner] instead of list[outer[inner]] (outer NOT A LIST)


#6

outer is a integer (produced by range), accessing integer by index will throw a getitem error


#7

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