Marvin
Marvin

Reputation: 421

How to remove values from a list of list in Python

I have a list as

[['Name', 'Place', 'Batch'], ['11', '', 'BBI', '', '2015'], ['12', '', 'CCU', '', '', '', '', '2016'], ['13', '', '', 'BOM', '', '', '', '', '2017']]

I want to remove all the '' from the list.

The code I tried is :

>>> for line in list:
...     if line == '':
...         list.remove(line)
...
print(list)

The output that it shows is:

[['Name', 'Place', 'Batch'], ['11', '', 'BBI', '', '2015'], ['12', '', 'CCU', '', '', '', '', '2016'], ['13', '', '', 'BOM', '', '', '', '', '2017']]

Can someone suggest what's wrong with this ?

Upvotes: 2

Views: 128

Answers (2)

Ma0
Ma0

Reputation: 15204

This is what you want:

a = [['Name', 'Place', 'Batch'], ['11', '', 'BBI', '', '2015'], ['12', '', 'CCU', '', '', '', '', '2016'], ['13', '', '', 'BOM', '', '', '', '', '2017']]
b = [[x for x in y if x != ''] for y in a]  # kudos @Moses
print(b)  # prints: [['Name', 'Place', 'Batch'], ['11', 'BBI', '2015'], ['12', 'CCU', '2016'], ['13', 'BOM', '2017']]

Your solution does not work because line becomes the entire sublist in every step and not the elements of the sublist.

Now it seems that you are trying to modify the original list in-place (without creating any additional variables). This is a noble cause but looping through a list that you are modifying as you are looping is not advisable and will probably lead to your code raising an error (IndexError or otherwise).

Lastly, do not use the name list since Python is using it internally and you are overwriting its intended usage.

Upvotes: 4

Moses Koledoye
Moses Koledoye

Reputation: 78536

You're running your test on the sublists not on the items they contain. And you'll need a nested for to do what you want. However removing items from a list with list.remove while iterating usually leads to unpredictable results.

You can however, use a list comprehension to filter out the empty strings:

r = [[i for i in x if i != ''] for x in lst]
#                       ^^ filter condition

Upvotes: 3

Related Questions