Flatten List in Python – Must-Know Interview Question!

Опубликовано: 15 Май 2026
на канале: DataEra
125
15

In this video, I’ll walk you through:
The difference between `isinstance(), append()` and `extend()`
A recursive function to flatten any nested list
Real-world interview-style Python thinking

Notes:
I/P
Nested_list=[1,2,3,[4,5,6,[7]]]

O/P
flatten_list= [1,2,3,4,5,6,7]


Append
Adds a single element to the end of the list.
The element can be any object (number, string, list, etc.).
If you append() a list, it gets added as a nested list.
li=[1,2,3]
li.append(4)
print(li)




Extend
Adds each element of an iterable (like another list, tuple, string) to the end of the list.
Effectively flattens the added iterable into the list.
li=[1,2,3]
li.extend([4,5])
print(li)

print(isinstance((1,2,3), tuple))


Method -1
def UnNest(nest_li):
li=[]
for i in nest_li:
if isinstance(i, list):
for j in i:
if isinstance(j,list):
for k in j:
li.append(k)
else:
li.append(j)
else:
li.append(i)
return li


Nested_list=[1,2,3,[4,5,6,[7,5,6,[10,11]]]]
print(UnNest(Nested_list))



Method -2 Recursive
def UnNest(nest_li):
li=[]
for i in nest_li:
if isinstance(i, list):
li.extend(UnNest(i))
else:
li.append(i)
return li


Nested_list=[1,2,3,[4,5,6,[7,5,6,[10,11,[11111,2222]]]]]
print(f"Recursive : ",UnNest(Nested_list))


#PythonForBeginners #learntocode #Python #Coding #Programming #PythonTutorial #FlattenList #InterviewPrep #appendVsExtend #RecursiveFunction #TechYouTube
#DataEngineering #DataScience #PythonForData #dataprocessing
#MachineLearning #PythonForAI #MLWithPython #ArtificialIntelligence #DeepLearning #AIEngineer
#SoftwareEngineering #PythonProgramming #TechInterview #DeveloperLife #CleanCode #ProgrammingTips #CodeNewbie #PythonDev #BackendDevelopment
#ProgrammingBasics #CollegeCoding #PythonProjects #TechCareers #CodingJourney