0

i want to remove None values in this list

input= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
        (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]

and get an output like

['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']
Ignatius
  • 2,745
  • 2
  • 20
  • 32
koti puppala
  • 9
  • 1
  • 3

5 Answers5

1

You need to iterate through the list (which contains tuples) and then iterate through each tuple. Check if each element of each tuple is None or not.

a = [
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
]
b = [element for sub_tuple in a for element in sub_tuple if element is not None]
print(b)

and you get

['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']

Ignatius
  • 2,745
  • 2
  • 20
  • 32
0

Try this:

input_= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
        (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]
output = []
for each in input_:
    newList = list(filter(None,each))
    output = output+newList
print(output)

Note: Do not use input as the variable it is a reserved keyword in python. It's okay if you have just used it for this post.

Hayat
  • 1,539
  • 4
  • 18
  • 32
0

If you wnat to strip, then concatenate -- list comprehension works really cleanly here without losing readability:

import itertools
stripped_lists = [ [x for x in sublist if x] for sublist in input_ ]

print(list(itertools.chain.from_iterable(stripped_lists )))

output:

['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']

Alternatively, if you concatenate and then strip, this is nice and short:

print(list(x for x in itertools.chain.from_iterable(aa) if x))
booleys1012
  • 671
  • 3
  • 9
0

First, flatten the data using list comprehension and then use filter() method to filter out the None values. filter() method will return a filter object. So we'll have to use the list() method to convert it back to a list:

flat_input = [item for sublist in input for item in sublist]
output = list(filter(None, flat_input))

This is the shortest solution I can imagine. Hope it helps !

Rabin Lama Dong
  • 2,422
  • 1
  • 27
  • 33
0

iterate the list then sub list if sub-list item is not None add to new list b

a = [
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
]
b=[]
for i in a:
    for j in i:
        if j:
            b.append(j)


print (b)
Pradeep Pandey
  • 307
  • 2
  • 7