Get a element from list, from pair of 3

Hello I have a list in which elemnets are in pair of 3 list given below,

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']

in above list elements are coming in pair of 3 i.e. (”, ”, ‘5000’) one pair, (”, ‘2’, ”) second pair, (‘mm-dd-yy’, ”, ”) third pair and so on.

now i want to check ever 3 pairs in list and get the element which is not blank.

(”, ”, ‘5000’) gives ‘5000’

(”, ‘2’, ”) gives ‘2’

(‘mm-dd-yy’, ”, ”) gives ‘mm-dd-yy’

and if all three are blank it should return blank i.e.

(”, ”, ”) gives ” like last 2 pair in list

so from the above list my output should be:

required_list = ['5000','2','1000','mm-dd-yy','15','dd/mm/yy','3','200','2','mm-dd-yy','','']

>Solution :

as it is fixed you have to create 3 pairs each time you can do with for loop by specifying step in range(start,end,step)

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']
res1=[]
for i in range(0,len(labels),3):
    res1.append(labels[i]+labels[i+1]+labels[i+2])
print(res1)

#List Comprehension
res2=[labels[i]+labels[i+1]+labels[i+2] for i in range(0,len(labels),3)]

print(res2)

Output:

['5000', '2', '1000', 'mm-dd-yy', '15', 'dd/mm/yy', '3', '200', '2', 'mm-dd-yy', '', '']

Leave a Reply