Ujjwal Mahajan
Ujjwal Mahajan

Reputation: 63

Replace an null element in a list with a value

I have an issue in the code snippet below:

I have a list of list, some of which is empty. First I want to replace the empty value with a value and then flatten it.

Here's the code snippet:

a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]

flat = ['0' if i == '[]' else i for element in a for i in element]  

But I'm unable to get the result. Kindly help

Upvotes: 0

Views: 1058

Answers (3)

User One
User One

Reputation: 513

Here is another way to flatten it to a 1-dimensional array, but it doesn't replace the empty array as 0.

from itertools import chain

a = [
    ['3'],
    ['4'],
    [],
    ['6']
]

flatten_list = list(chain.from_iterable(a))

print(flatten_list)

Upvotes: 0

Udipta kumar Dass
Udipta kumar Dass

Reputation: 151

Try the below code,

Code1 -

a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]
updated = [val[0] if val else '0' for val in a]
print(updated)

Code2 (For understanding purpose in a long form) -

a = [['3'] , ['4'], [], ['6']]  #I want to get ['3', '4', 0 , 6]

for i in range(len(a)):
    if a[i] == []:
        a[i] = '0'
    else:
        a[i] = a[i][0]
print(a)

Both the above code fulfills your requirment.

Upvotes: 1

Sayse
Sayse

Reputation: 43300

You can use next with a default value

flat = [next(x, "0") for x in a]

or just the fact that an empty list is falsy

flat = [x[0] if x else "0" for x in a]

Upvotes: 3

Related Questions