Analyst
Analyst

Reputation: 137

Delete None in python list

Q1.
enter image description here

I want to get output as:

[Randy, Shaw]

Output Looks like

['Randy', 'None', 'None', 'Shaw', 'None', 'None']

But it is not removing 'None' values.
Here is my code..

from openpyxl import load_workbook
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
print(workbook.get_sheet_names())

sheet=workbook.get_sheet_by_name('marks')

iterheaders = iter(sheet[1])
headers = [str(cell.value) for cell in iterheaders if cell is not None and cell != '']

Keyword_list = list(filter(None, headers))

I even tried the following but it didn't work either:

Keyword_list = [i for i in headers if (None) != len(i)]

Q2. In the same code what if I want to get the sheet by its index rather than by its name in openpyxl. How do I do that?

Upvotes: 2

Views: 1364

Answers (2)

Ajax1234
Ajax1234

Reputation: 71461

You can filter like so:

s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']

s = [i for i in s if i != "None"]

Keep in mind that in your list you have the string "None", not the object None

For Q2:

workbook = load_workbook('C:/Users/Desktop/test.xlsx')

sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.

Upvotes: 2

Chris
Chris

Reputation: 22963

Your none values are not literal None type values. Their strings. Therefore, you need to test them against strings. eg:

>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>

Upvotes: 1

Related Questions