Using a list of lists in a function


#1

Here’s the link
https://www.codecademy.com/courses/learn-python/lessons/lists-and-functions/exercises/using-a-list-of-lists-in-a-function?action=lesson_resume

The Error message shown here is
File “python”, line 8
return results
^
SyntaxError: invalid syntax

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



print flatten(n)

How is the code supposed to be?

Thanks


#2

Let’s walk through your code and discuss it.

Issue 1

for i in list[numbers]:

What is list? You have a loop here that should be walking through the numbers to get at each number within that list. Think about it.

The loop before it gives you a list of numbers.

Loop 1 -> numbers will be [1, 2, 3].

In your second loop, you then want to iterate (loop) through each of the items in that new list of numbers.

Issue 2:

results=results.append(lists(numbers[i])

Here, you’re using the variable parameter lists as a function, i.e. lists(). It’s not a function. Right? It’s a list of lists.

Once you rework your second for loop as I mentioned above, you’ll get a single number out of numbers. It’s not a key. Rather, it’s a value. You want to append that value into your results list.

Lastly with this one, .append() is adding the new item into the list. It doesn’t return anything back as you are doing here results=results.append().

Issue 3

Look at the `return. It’s within the 1st loop. Is that when you want to return the results?


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



print flatten(n)

In issue 2:
I’m calling the append function to append the numbers(the two lists in the lists) to result. So would this be right results.append(lists[numbers[i]]
Well, I’m still confused about returning the results since there’s an error is coming as invalid syntax.

Thanks


#4

You getting an invalid syntax because i is not a key or index to the list of numbers. It’s the inner list. To see what I mean, do this:

  for numbers in lists:
    print numbers

    for i in range(len(numbers)):
      print i

      results.append(lists[numbers[i]]
      return results 

Look at the results. numbers will be:

Loop 1 -> [1, 2, 3]
Loop 2 -> [4, 5, 6, 7, 8, 9]

Then you can repeat that looping pattern to loop through numbers and iterate each number in the 2nd for loop. You don’t need len or range.


#5

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