3

I have a list of strings, some of them are None. i want to get a new list of all the Indexes of None.

list = ['a', 'b', None, 'c' ,None, 'd']

using the function index

n = list.index(None)

will only return the first appearance, n= 2, while i want to see n= [2,4]. thanks you.

Zusman
  • 606
  • 1
  • 7
  • 31

3 Answers3

15

Try enumerate:

l=[i for i,v in enumerate(list) if v == None]

Or range:

l=[i for i in range(len(list)) if list[i] == None]

Both cases:

print(l)

Is:

[2,4]

Big Note: it is not good to name variables a existing method name, that overwrites it, (now it's list), so i would prefer it as l (or something)

I recommend the first example because enumerate is easy, efficient.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

Faster way. Very useful in case of long list.

list = ['a', 'b', None, 'c' ,None, 'd']
import numpy as np
print(np.where(np.array(list) == None)[0])

Output :

[2 4]

In case you need list of index :

print(np.where(np.array(list) == None)[0].tolist())
>>> [2, 4]
LMSharma
  • 279
  • 3
  • 10
2

Here's something different but it doesn't use list comprehension:

>>> l = ['a', 'b', None, 'c' ,None, 'd']
>>> out = []
>>> for _ in range(l.count(None)):
    out.append(l.index(None))
    l[l.index(None)] = "w"


>>> out
[2, 4]
>>> 
Nouman
  • 6,947
  • 7
  • 32
  • 60