-2

Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. For example, if the input is [[1,1],2,[1,1]], then the output is [1, 1, 2, 1, 1]. If the input is [1,[4,[6]]], then the output is [1, 4, 6].

Would anyone be able to advise me as to where the code below went wrong? I am just starting out with python.

def eb34(list1):
   
    flat_list = []
    
    for i in range(len(list1)):
        if type(list[i]) == list:
            flat_list += flatten(list1[i])
        else:
            flat_list.append(list1[i])
        
    return flat_list
Mark
  • 90,562
  • 7
  • 108
  • 148
Alvin Teoh
  • 1
  • 1
  • 1
  • 2
    You are calling a function called `flatten()` — where is that defined? I only see a function called `eb34`. There seems to be several problems here. I would start by looking at and understanding the errors. – Mark Jul 17 '22 at 19:32
  • where you wrote `if type(list[i]) == list:` you probably want `if type(list1[i]) == list:` – Ignatius Reilly Jul 17 '22 at 19:32
  • Maybe `flatten()` is supposed to be `eb34()`?? – Ignatius Reilly Jul 17 '22 at 19:35
  • @alvin-teoh, One big source of bugs in python (and any programming language) is the fact that they don't understand what you "want" to say, but only what you actually write. So, it pays to take the time to review every single name a couple of times when debugging, specially if you have been re-writing your code many times. – Ignatius Reilly Jul 17 '22 at 19:39
  • Related, though I don't think it's a dupe: https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists – SuperStormer Jul 17 '22 at 19:42
  • The code above would actually be provided in the course material (albeit slightly changed). When things did not work out, I used the original code as it was. But it seems that there are errors as well. – Alvin Teoh Jul 17 '22 at 19:44
  • The statement `type(list[i]) == list` implies that there was a variable name `list` (that you can index as `list[i]`. "list" is a reserved keyword, and therefore should never be used to name variables. If it was like that in your reference code, then yes, the reference was wrong. – Ignatius Reilly Jul 17 '22 at 19:48
  • Would flatten() would be a built-in function? – Alvin Teoh Jul 17 '22 at 19:50
  • Does this answer your question? [How do I make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists) – funnydman Jul 17 '22 at 19:54
  • No, they were expecting you to write a recursive function, called `flatten()`, that would call itself in each recursion. If `eb34` is also part of the course material, well... another mistake. Maybe they're misleading you to increase the challenge :) – Ignatius Reilly Jul 17 '22 at 19:56

4 Answers4

2

You can use recursion:

def flatten(arg):
    if not isinstance(arg, list): # if not list
        return [arg]
    return [x for sub in arg for x in flatten(sub)] # recurse and collect

print(flatten([[1,1],2,[1,1]])) # [1, 1, 2, 1, 1]
print(flatten([1,[4,[6]]]))     # [1, 4, 6]

Or to make a generator,

def flatten(arg):
    if not isinstance(arg, list): # if not list
        yield arg
    else:
        for sub in arg:
            yield from flatten(sub)

print(*flatten([[1,1],2,[1,1]])) # 1 1 2 1 1
print(*flatten([1,[4,[6]]]))     # 1 4 6
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

I don't know from where you are calling flatten() in your code. I am giving you a solution with the other information you have given.

def eb34(list1):
    flat_list = []
    for i in list1:
        if isinstance(i, list):
            for j in eb34(i):
                flat_list.append(j)
        else:
            flat_list.append(i)
    return flat_list
halfer
  • 19,824
  • 17
  • 99
  • 186
Divya Prakash
  • 898
  • 1
  • 6
  • 14
0

You can recursively flatten it:

def flatten_recursively(lst_in):
    lst_out = []
    for i in lst_in:
        if type(i) == list:
            for j in flatten_recursively(i):
                lst_out.append(j)
        else:
            lst_out.append(i)
    return lst_out

Also check out this answer, although you might have to adjust it to Python 3+: https://stackoverflow.com/a/10824420/18189622

ewz93
  • 2,444
  • 1
  • 4
  • 12
-1

The easiest way to make a flat list from nested lists is to use the itertools module. The itertools module has a function called chain that takes a list of lists and returns a single list.

 >>> import itertools
 >>> nested_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 >>> flat_list = list(itertools.chain(*nested_lists))
 >>> flat_list
 [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 1
    The question is obviously an exercise where student is supposed to come with an algorithm using atomic tools, not importing modules that "solve the problem for you". Also, please check how to answer [HW questions](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). – Ignatius Reilly Jul 17 '22 at 19:42
  • This also produces an error with the first example input provided. – Mark Jul 17 '22 at 20:04