# Using a list of lists in a function

#1

===========================================================
(1) Apparently the right thing to put there is “results.append(number)”. But I put “results = results + number” and I got the following result in the output window. What was wrong about my code?

Traceback (most recent call last):
File “python”, line 11, in
File “python”, line 8, in flatten
TypeError: can only concatenate list (not “int”) to list

*Correct code is as indicated below :

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

def flatten(lists):
results = []
for numbers in lists:
for number in numbers:
results.append(number)
return results

print flatten(n)

==========================================================

(2)The output varies depending on how many indentations I make in front of “return”. What is the difference?

A.
def flatten(lists):
results = []
(3)for numbers in lists:
(5)for number in numbers:
(6)results.append(number)
(3)return results

print flatten(n)

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

B.
def flatten(lists):
results = []
(3)for numbers in lists:
(5)for number in numbers:
(6)results.append(number)
(5)return results

print flatten(n)

#Output = [1, 2, 3]

==========================================================

#2

`results = results + number`, the `+` will extend the list, example

``````print [1,2,3] + [4,5,6]
``````

so using list extending, its possible, but then you only need a single loop

By default a function returns None at the end, if we want to return something else at the end of the function, we can use the return keyword (given its at the end, return will end the function)

so when you place return inside a loop, it will break the loop in order to end the function

#3

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