-3

Since stackoverflow refuses to let me answer this question as I'm a new user, I'll post my question and answer here. (The question is not present in the list of "Similar questions," either.)

QUESTION:

How can I flatten the following list of lists and ints?

[0, 10, [20, 30], 40, 50, [60, 70, 80]]

  • 2
    Why can't you use any of the MANY answers to the question you linked to? – Scott Hunter May 02 '22 at 18:02
  • 2
    This question already has plenty of duplicates, it doesn't need yet another. [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – Pranav Hosangadi May 02 '22 at 18:04
  • @PranavHosangadi You can blame StackOverflow for disallowing me to answer or comment. My answer is different than the others there. No importing. Nothing higher level than fundamental. – It's All Waves May 02 '22 at 18:08
  • @ScottHunter because I don't like them. I'm a new coder and I want to avoid importing or using anything I haven't already had a need to learn. That page served as an intro to some higher level stuff for me, but I won't use any of that until I encounter the need multiple times. This is how I learn. – It's All Waves May 02 '22 at 18:09
  • 1
    What you've linked is an _answer_, not a question. There's no reason you can't answer that question. You can't edit or comment on other people's answers, but there's no reason a new user can't add an answer. If I'm mistaken and new users are indeed prevented from adding answers, then the solution is not to bypass these restrictions by creating a duplicate question. Instead ask a good question that will get you the [reputation](/help/privileges) you need. – Pranav Hosangadi May 02 '22 at 18:10

2 Answers2

1

lst = [0, 10, [20, 30], 40, 50, [60, 70, 80]]

new_lst = []
for a in lst:
    if type(a)!=list:
        new_lst.append(a)
    else:
        new_lst.extend(a)

print(new_lst)

OUTPUT

[0, 10, 20, 30, 40, 50, 60, 70, 80]

Below is working even if the input list also contains float, tuple and string.

lst = [1,2,[3,4],"hello world"]

new_lst = []
for a in lst:
    if isinstance(a,int) or isinstance(a,float) or isinstance(a,str):
        new_lst.append(a)
    else:
        new_lst.extend(a)

print(new_lst)

OUTPUT

[1, 2, 3, 4, 'hello world']
Sharim Iqbal
  • 2,724
  • 1
  • 4
  • 24
-1

V1 -- works for a list of lists, ints, strings:

def FlattenAllItems(lst):
    if not lst: return []
    flattened = []
    for item in lst:
        if type(item) != list:
            item = [item]
        for i in item:
            flattened.append(i)
    return flattened

V2 -- adds ability to unpack a tuple, as well:

def FlattenAllItems(lst):
    if not lst: return []
    flattened = []
    for item in lst:
        if type(item) == tuple:
            item = [*item]
        if type(item) != list:
            item = [item]
        flattened.extend(item)
    return flattened

Thanks for reading!