Difference between methods of iterating through a list


#1

Hello

I'm trying to understand why the following doesn't work:

> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>
> def flatten(lists):
>     results = []
>     for numbers in lists:
>         for x in numbers:
>             results.append(numbers[x])
>     return results
>
> print flatten(n)

Yet, this works:

> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>
> def flatten(lists):
>     results = []
>     for numbers in lists:
>         for x in range(len(numbers)):
>             results.append(numbers[x])
>     return results
>
> print flatten(n)

If, "for numbers in lists:" iterates through the list of lists successfully, why can't "for x in numbers" iterate through the numbers which are within the lists of the parent list?


#2

it can, in fact, it is. The problem is that x contains the values from the list, so you would need to append x directly to result

in the second code, you use range(), this will give you indexes, which you need to use to retrieve the values from the list (using square brackets)

because the first approach contains the values, you might get a value higher then the highest index, throwing an indexerror


#3

Oh so with the 1st function I ended up using each number in the list as an index, meaning if my list has 3 numbers but my index is [3] that means I will be asking for a value which does not exist?
Meaning I just need to change results.append(numbers[x]) to results.append(x) for the 1st function to work


#4

yes, exactly. You seem to understand perfectly :slight_smile:


#6