Python 12. Lists and Functions - 18. Using Lists of Lists by range method


#1

Hi there, I'm trying to use the following code:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

Add your function here

def flatten(lists):
results =[]
for numbers in range(len(lists)):
for i in range(len(numbers)):
results.append(numbers[i])
return results

print flatten(n)

Which gives me the following error:
Traceback (most recent call last):
File "python", line 12, in
File "python", line 7, in flatten
TypeError: object of type 'int' has no len()

I understand that simply running through the list is more efficient so please don't give me that answer, I just don't understand why my implementation of range doesn't work. Thank you!


#2

@blogslayer69506 ,

What does the variable, numbers, represent here, and how should that variable be used in the code that follows? ...

for numbers in range(len(lists)):

#3

My understanding is that numbers represents the column index in the 2D array. That allows me to use it in the inner loop to access the individual items in the inner lists.


#4

Then what is len(numbers) in this statement, which is the line that follows? ...

for i in range(len(numbers)):

#5

The length of the inner list, right? i.e in the case of the first pass - length of [1,2,3]


#6

No, if numbers is a column index, then it is an int. What, then, is len(numbers)?

TypeError: object of type 'int' has no len()

#7

Ahahaha! I'm an idiot! :grinning: Of course numbers is an integer

Ok, so numbers is an index, so to reference the list instead I'd have to use len(numbers[i])? That throws an exception that tells me i isn't defined yet, which makes sense I guess. Does that mean that I'm forced to use the other method of reading through the list in this case?

Or better Yet - how can I convert the code below using the range function?

def flatten(lists):
    results =[]
    for numbers in lists:
        for i in numbers:
            results.append(i)
    return results

#8

numbers is an index of the lists object. numbers is not a great name for an index, but that's what you have.

To use it as an index, you could do this ...

for j in range(len(lists[numbers])):

Then j would be an index to use within an inner list.

You could rename some variables to make things clearer. For example, i and j would be better names for indexes than numbers. You could use i for the outer loop and j for the inner loop. In that case, we might see something like lists[i][j] in the inner loop.


#9

Oh trust me these aren't my choices for variable names - it's what the tutorial requires (numbers at least).
And yay, success!.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here

def flatten(lists):
    results =[]
    for numbers in range(len(lists)):
        for j in range(len(lists[numbers])):
            results.append(lists[numbers][j])
    return results      


print flatten(n)

[1, 2, 3, 4, 5, 6, 7, 8, 9]
None

#10

Glad it worked ... :relaxed:


#11