pythonintermediate10 minutes
Build a Function to Flatten Nested Lists by One Level
Create a Python function that takes a list containing nested sublists and returns a new list flattened by exactly one level. This means only the first level of nested lists should be expanded, while deeper nested structures remain intact.
Challenge prompt
Write a function named flatten_one_level that accepts one parameter: a list which may contain elements or nested lists at any depth. Your function should return a new list where only the first level of nested lists is flattened into the main list. Deeper nested lists inside those sublists should remain nested as they are.
Guidance
- • Iterate over each element in the input list and check whether it is a list.
- • If the element is a list, extend its items into the result list instead of adding the entire list as a single element.
- • If the element is not a list, append it normally to the result list.
Hints
- • Use Python's isinstance() function to check if an element is a list.
- • Using list.extend() is helpful when you want to add elements of a list rather than the list itself.
- • Avoid flattening recursively or using nested loops that go beyond one level.
Starter code
def flatten_one_level(input_list):
# Your code here
passExpected output
flatten_one_level([1, [2, 3], [4, [5, 6]], 7]) # returns [1, 2, 3, 4, [5, 6], 7]
Core concepts
list manipulationtype checkingiteration
Challenge a Friend
Send this duel to someone else and see if they can solve it.