# 18/18

I need a fresh set of eyes to tell me what’s wrong with my code:

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

def flatten(lists):
results =
for numbers in lists:
for i in numbers:
results.append(i)
return results

print flatten(n)

Oops, try again.
flatten([[1, 2], [3, 4]]) returned [1, 2] instead of [1, 2, 3, 4]
tkx

There are several ways to flatten lists,

Examples:

List Comprehension

``````n = [[1, 2, 3], [4, 5, 6, 7, 8, 9], 10, 11, 12]

def flatten(alist):
return [item for blist in alist for item in blist]
``````

For loops

``````def flatten(lists):
flat_list = []
for item in lists:
for it in item:
flat_list.append(it)
return flat_list
``````

There are a bunch of other ways to do this also but these two are the closest to your skill level.

7 Likes

Great, that worked! Thank you!

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

def flatten(lists):
[tab]results =
[tab]for numbers in lists:
[tab][tab]for items in numbers:
[tab][tab][tab]results.append(items)
[tab]return results
print flatten(n)

2 Likes

should be [tab][tab][tab] should it not?

1 Like

yup !
Take care of indentation in your code!!
Thanks @cssjumper36549 …anyways, [tab] was missing in code here only !
Happy Coding!

Thank you for the simple way to complete this task!

Here’s a little trick for you guys

Whenever you would like to paste code, since this forum supports Markdown Syntax you can use three backticks before and after your code block like so:

```
def my_func(x):
my_var = 0
if x > my_var:
sum = my_var + x
else:
print “Odelay!”
return sum
```

and it will retain proper indentation and even have nifty syntax highlighting:

``````def my_func(x):
my_var = 0
if x > my_var:
sum = my_var + x
else:
print "Odelay!"
return sum
``````
2 Likes

@denisaltroy for sure ! Thanks

1 Like

I have a new `flatten` function, I use this in one of my programs because I get a list of tuples which In then add to a list the end result being a list of a list of tuples.

In needed to preserve the tuples I have to write a recursive function that would endlessly search for lists in the container objects, So this function I have here will flatten any data that contains a list as the topmost item, because if you have a dict of list of tuples you will want to preserve that.

With out further adieu here is my new flatten function.

``````def flatten(a_list):
"""
Flattens the given list of an arbitrary amount of lists/items into a single list with all values
:param a_list: Pass the list object you wish to flatten, no list will be left with in. Also maintains order.
:return: Returns this function with the hold list as an argument if there
are any list objects, else it returns the held list.
"""
hold = []
for item in a_list:
if list == type(item):
for it in item:
hold.append(it)
else:
hold.append(item)
return flatten(hold) if any(type(part) == list for part in hold) else hold

``````
1 Like

Thank you. The hidden rule about indenting the code lines can be really tricky.