18. Using a list of lists in a function - range(len(x)): not working as expected


#1




18. Using a list of lists in a function

From what I understood from previous sections of this course, the use of the "for x in y" could also be written as "for x in range(len(y))" for use when itterating through loops. Indeed I have returned through the previous examples which also used listsof integers and had no issues in itterating through those lists.

I have since searched through the forums and seen that everyone has used "for x in y" format, though I do not understand why that would work and not the "range(len(y))". Either I've missed something obvious or there's a blank-spot in a part of the course setting out the limits of what the "range(len(y))" version can do.

Error:

Traceback (most recent call last):
  File "python", line 25, in <module>
  File "python", line 19, in flatten
TypeError: object of type 'int' has no len()

My biggest confusion being that the TypeError saing "object of type 'int' has no len()". From my understanding, each of the objects being handed into the For loops are lists ("lists" and "numbers" respectively), both of which have a definite length in the array.


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 number in range(len(numbers):
            results.append(number)
    return results

print flatten(n)


#2

using range gives you indexes:

aList = ['a','b','c']
for x in range(len(aList)):
     print x

this will output:

0
1
2

this matches with indexes of aList, so then we can do:

aList = ['a','b','c']
for x in range(len(aList)):
     print aList[x]

to get the values from the list. And this is where you go wrong:

    for numbers in range(len(lists)):
        for number in range(len(numbers):

numbers contains an integer, and integers do not have a len attribute, so then this: len(numbers) throws an error

list and strings do have lenght, integers do not


#3

Ok, that took a little bit to understand, but I get what you mean.

I don't feel the course actually covered that in a clear enough way, though I imagine it's a very uncommon issue to start with.
Thanks for the prompt reply!


#4

using a for loop without range:

aList = ['a','b','c']
for x in aList:
     print x

gives you the values from the list directly.

the advantage of using range() is that you can use the indexes to update elements in the list:

aList = [4,5,6]
for x in range(len(aList)):
    aList[x] = aList[x] + 3
print aList

hope that clarifies. So for your code, i wouldn't use range()

For loops will be covered more later, so don't panick yet :wink:


#5

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