Using a list of lists in functions - Console errors


#1




Using a list of lists in functions


Error Message:
Traceback (most recent call last):
File "python", line 12, in
File "python", line 8, in flatten
NameError: global name 'result' is not defined

I do not understand the error with my code, in particular, such area where it denotes that 'result' is undefined.
But it is defined, it is that its assigned value is empty. Such that:

results = []

Any clarification is heavily appreciated in advance. Here is the code for your reference:


n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    for numbers in lists:
        for number in numbers:
            results.append(numbers)
    return result



print flatten(n)


#2

This is what is defined. Check your spelling.


#3

I checked back at the spelling. It is correct.
I was supposed to create an empty string called results and eventually .append() numbers from the numbers lists which are from the n list to return the numbers from the numbers list with only one set of brackets, like such, from

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

#4

results is the empty list you defined, and are appending to. The return result is not defined. Add the missing s.

Python actually has a cool feature: We can add one list to another.

[1, 2, 3] + [4, 5, 6] == [1, 2, 3, 4, 5, 6]

which means we do not need a nested loop. Just the outer one.


#5

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