18. Using a list of lists in a function


#1

I don't know what i'm doing wrong here. I don't know if the indentation or syntax is the problem.
Code:

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

Error message:

Traceback (most recent call last):
  File "python", line 9, in <module>
  File "python", line 6, in flatten
NameError: global name 'num' is not defined

Wasn't num already defined though? My code has num as a number in an inner list.


#2

Hi @auncodes ,

No, actually, num has not been defined.

This statement establishes the variable, l, to represent each inner list as the outer loop iterates ...

for l in lists:

Therefore, you need to modify this inner loop header to access that variable rather than the undefined name, num ...

for i in num:

#3

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