X

Flatten list item from Column – Python [Data Cleaning]

Hi folks. , Hope you are doing well. So here today I’m going to present you a scenario that we are going to solve , very simple concept yet very useful and very effective in day to day life for every data engineering approach in the field of data science. So i’m going to write and article about how we can flatten the list of column-  means list of list value into single list

Problem concept

Suppose you have list of list and again a list inside of that.  to Much confusion !! 😅, See below I’ve added an example for the give problem 👇

 

Column_a =  [['Apple','Mango'],['Orange','Banana'],('t1','t2')]

Here –  Column A contains list of list and tuples. and we want to flat it to single list like this –

Column A - ["Apple","Mango","Orange","Banana","t1","t2"]

So I think we all clear about the problem and solution which we are going to solve.

  1. With only list value we are going to flat

1. Here for only list we are going to put list comprehension to solve this problem.

new_fruit = [Fruit for sublist in Column_a for Fruit in sublist]
print(new_fruit)

So easy and here we go with the easiest way to flatten the list of list + tuple

['Apple', 'Mango', 'Orange', 'Banana', 't1', 't2']

Categories: Python
Jamaley Hussain: Hello, I am Jamaley. I graduated from Staffordshire University and have always been passionate about Computers, Technology, and Generative AI. Currently, I work as a Senior Data Scientist (AI/ML) and I’m also the founder of TechJunkGigs, a platform dedicated to helping programming students with tutorials on Machine Learning, Data Science, Python, LLM, RAG, Generative AI, and NLP. What started as a blog has now evolved into a valuable resource for students, and I'm committed to sharing knowledge to help them stay updated with industry trends
Related Post