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 did my graduation from StaffordShire University UK . Fortunately, I find myself quite passionate about Computers and Technology.
Related Post