This handles both of your cases, and I think will solve the general case, without any for loops:
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
Related Contents:
- List comprehension on a nested list?
- Extract first item of each sublist
- Basics of recursion in Python
- How to do a recursive sub-folder search and return files in a list?
- Python recursion with list returns None [duplicate]
- Finding max value in the second column of a nested list?
- Function with varying number of For Loops (python)
- Is there a recursive version of the dict.get() built-in?
- Comprehension on a nested iterables?
- Search for a key in a nested Python dictionary
- How can I use list comprehensions to process a nested list?
- How to find common elements in list of lists?
- Confusing […] List in Python: What is it?
- Given a list of elements in lexicographical order (i.e. [‘a’, ‘b’, ‘c’, ‘d’]), find the nth permutation – Average time to solve?
- Turning a list into nested lists in python
- Split a Pandas column of lists into multiple columns
- How do I find the duplicates in a list and create another list with them?
- Shuffling a list of objects
- Split a string by a delimiter in python
- Is there a zip-like function that pads to longest length?
- Access multiple elements of list knowing their index
- Permutations between two lists of unequal length
- Count frequency of words in a list and sort by frequency
- Pandas DataFrame stored list as string: How to convert back to list
- Variable assignment and modification (in python) [duplicate]
- Python’s insert returning None?
- Check if two unordered lists are equal [duplicate]
- Dynamic variable in Python [duplicate]
- Python 3 turn range to a list
- Check if all elements of a list are of the same type
- Find the item with maximum occurrences in a list [duplicate]
- Take the content of a list and append it to another list
- Sorting Python list based on the length of the string
- Accessing a value in a tuple that is in a list
- Pythonic way to create union of all values contained in multiple lists
- How to empty a list?
- How do I loop through a list by twos? [duplicate]
- remove None value from a list without removing the 0 value
- [] and {} vs list() and dict(), which is better?
- How do I split a string into a list?
- How to flatten a nested JSON recursively, with flatten_json
- Convert list into a dictionary [duplicate]
- Unpack list to variables
- How to convert list of tuples to multiple lists?
- Identify duplicate values in a list in Python
- How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?
- Creating a tree/deeply nested dict from an indented text file in python
- Find starting and ending indices of sublist in list
- Adding a string to a list using augmented assignment
- How to parse a string and return a nested array?