0

I'm a new Python learner and I have an assignment to extract all elements from a simple list (any depth) and unpack it into a new list of simple elements.

Something like this:

lst = [1, 2, [3, 4, [5, 6, 7]]]

new_lst = [1, 2, 3, 4, 5, 6, 7]

I can't use functions to do it directly.. can only use loops (for/while) or conditional statements (if elif else) or python functions like "append".

Any ideas?

DeadChex
  • 4,379
  • 1
  • 27
  • 34
  • 2
    Lots of good answers here: [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) – JNevill Sep 23 '22 at 15:17
  • 1
    Since the list can be arbitrarily deep, you'll need to use something like `isinstance(item, list)` and change your behavior based on that result – 0x5453 Sep 23 '22 at 15:19
  • If you are still stuck after reading through the answers in that link, feel free to edit this question with the code you are writing and where you are stuck and we can help you through it from there. – JNevill Sep 23 '22 at 15:23
  • @JNevill that link is pretty good, but as I said, I have the limitation of only using “simple” code tools like loops and conditional statements… the first answer is what I used for a list of depth “2”… but if one of the lists inside the first one also have a list as one of the elements, it won’t work (ie it works for [1, 2, [3, 4]] but not for [1, [2, [3, 4]]]) – tbrizzo Sep 23 '22 at 20:35
  • There are dozens of answers there that all solve in different ways. Would [this one](https://stackoverflow.com/a/70285413/2221001) not fit your needs? – JNevill Sep 26 '22 at 14:15
  • Sorry for not responding sooner. I generally only haunt SO during weekdays to keep my hands busy during meetings. I just tested that answer with your nested list and it spit out your desired results and only uses simple built in python stuff. – JNevill Sep 26 '22 at 14:24
  • Welcome to Stack Overflow. Please read [ask]. Here are some hints for asking questions properly: 1. **Do not mention** your level of skill or anything else - the question should be about **the problem, not** you. 2. Write the title last, and make sure it describes the problem accurately. If the lists can be nested to "any depth", then that is **not** simply "a list of lists", so don't say that. 3. Make sure to **ask a question** that is clear and specific - "Any ideas?" [does not qualify](https://meta.stackoverflow.com/questions/284236). – Karl Knechtel Sep 30 '22 at 20:38
  • 4. [Look for existing solutions](https://meta.stackoverflow.com/questions/26159) before asking, for example by [using a search engine](https://duckduckgo.com/?q=python+flatten+nested+list). If you find that you must write code yourself and get stuck with it, figure out exactly where you are stuck, and why; then ask specifically about that part, not about the overall task. – Karl Knechtel Sep 30 '22 at 20:39

0 Answers0