Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Flatten Nested Lists in Python

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Flatten Nested Lists in Python. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

A Convex function may receive a list containing values and other lists. Write a function that flattens the structure into a single list while preserving the left-to-right order of every value.

Formal Specification

Implement flatten_nested(values), where values is a list whose elements are either integers or nested lists with the same structure. Return a new list containing all integers in depth-first, left-to-right order. Empty lists contribute no values.

Do not mutate the input list. The nesting depth is valid for Python's recursion limit.

Constraints

  • 0 <= len(values) <= 10^4
  • Each leaf value is an integer between -10^9 and 10^9
  • The total number of lists and integers is at most 10^5
  • Nesting depth does not exceed Python's recursion limit
  • The input must not be modified

Function Signature

def flatten_nested(values):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output