Using a list of lists in a function- I need help


#1

I cannot figure this out this is my code:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

Add your function here

def flatten(lists):
results = ''
for number in lists:
number.append(results)
return results

print flatten(n)

the error message is: flatten([[1, 2], [3, 4]]) returned ‘’ instead of [1, 2, 3, 4]


#2

Let’s walk through a function strategy and then you can convert it into code.

First of all, results = '' is not a string, but rather a list. Therefore, initialize it to be an empty list: results = []. That’s where you will store the results as you loop through the numbers.

Does that make sense? If no, let’s talk about it.

Let’s think about the dataset you are getting within this function. It’s a list of lists. n has 2 lists inside of it. Right?

The first loop for number in lists: is looping through the items in the n list:

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

Notice that you get another list with the loop. Right?

Think about how you can loop through those inner lists to append each number into your results list. Give that a try.


#3

I’m confused, I fixed the result but I don’t understand what you said after that. Do you want me to create two variables so I can add them together?


#4

Let’s take a look at the what the loop is giving you. Put a print statement in your code like this:

def flatten(lists):
  results = []
  for number in lists:
    print number
  
  return results

Let’s start there. What is outputted to the terminal? It’s each inner list. Right?

Then you need a 2nd loop to iterate through those numbers.

def flatten(lists):
  results = []
  for numbers in lists:
    print numbers
    # loop through the numbers here as the 2nd loop
      print number
  
  return results

#5

Ok I tried what you said and I played around with it and finally got it! This was my final code:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

Add your function here

def flatten(lists):
results = []
for number in lists:
results += number
return results

print flatten(n)

And this printed in the console:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Thanks for all your help!