Souvik Ray
Souvik Ray

Reputation: 3018

Replacing null values in a list with values of another list

I have two lists

lis1 = [12,34,56,89]
lis2 = [10,34,90,108,None,None,None,None]

How do I replace None values with values of lis1 without creating any new list?

The end result should be

lis2 = [10,34,90,108,12,34,56,89]

So far what I tried

lis2 = [i for j in lis2 for i in lis1 if j is None]

But this gives me an incorrect list.

Upvotes: 2

Views: 3459

Answers (4)

Himaprasoon
Himaprasoon

Reputation: 2659

A shorter way:

lis2 = [1, None, None, 4, 5, None, 7, None]
lis1 = [2, 3, 6, 8]
list2 =[i if i else lis1.pop(0) for i in lis2]
print(list2)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 1

Matthew Wu
Matthew Wu

Reputation: 64

(Expanding on COLDSPEED's answer, which is cleaner if all the Nones come at the end of the list.)

# Replace Nones in list 2 with elements from list 1
> lis1 = [2, 3, 6, 8]
> lis2 = [1, None, None, 4, 5, None, 7, None]

# Index of next element to use from list 1
> j = 0

> for i in range(len(lis2)):
    if lis2[i] == None:
        lis2[i] = lis1[j]  # Replace a None with something from list 1
        j += 1  # Use the following element next time

> lis2
[1, 2, 3, 4, 5, 6, 7, 8]

Again, you'll have to do some checking if it's not guaranteed that the length of list 1 is the same as the number of Nones in list 2.

Upvotes: 1

cs95
cs95

Reputation: 402483

Here's one possible approach:

In [870]: lis2[lis2.index(None):] = lis1

In [871]: lis2
Out[871]: [10, 34, 90, 108, 12, 34, 56, 89]

Subslice assignment. The assumption here is that lis2 has as many None values as lis1 has elements and that they all lie at the end.


To break it down:

  1. lis2.index(None) returns the first index of None in the list

    In [873]: lis2.index(None)
    Out[873]: 4
    
  2. You can obtain a subslice of lis1 like this:

    In [874]: lis2[lis2.index(None):]
    Out[874]: [None, None, None, None]
    
  3. Just reassign lis2 to this slice.

Upvotes: 2

voidpro
voidpro

Reputation: 1672

Here is a way.

> lis1 = [12,34,56,89]
> lis2 = [10,34,90,108,None,None,None,None]
> lis2 = [x for x in lis2 if x is not None]
> lis2
=> [10, 34, 90, 108]
> lis2 += lis1
> lis2
=> [10, 34, 90, 108, 12, 34, 56, 89]

First remove all None from lis2. Then extend lis2 with lis1

Upvotes: 1

Related Questions