pythonintermediate10 minutes
Build a Function to Flatten a Nested List of Integers
Create a Python function that takes a nested list of integers and returns a flat list containing all the integers in their original order.
Challenge prompt
Write a function named flatten_list that accepts a single parameter: a list which can contain integers or other lists (which themselves may contain integers or other lists, and so on). Your function should return a new flat list containing all the integers from the nested structure in the same left-to-right order.
Guidance
- • Use recursion to handle arbitrarily nested lists.
- • Check the type of each element to decide if it’s an integer or a sublist.
Hints
- • Use isinstance(element, list) to check if an element is a list.
- • If an element is an integer, append it to the result list; if it's a list, recursively call flatten_list on it.
Starter code
def flatten_list(nested_list):
# Your code here
passExpected output
flatten_list([1, [2, [3, 4], 5], 6]) # returns [1, 2, 3, 4, 5, 6]
Core concepts
recursionlist manipulation
Challenge a Friend
Send this duel to someone else and see if they can solve it.