-6

This is the output after some processing. I want to remove the null/empty values from the array.

['HOST1', '6667', 'CHANNAME1', '', 'CHANNAME2', '', '', 'HOST2', '6667', 'CHANNAME3', '', '', '']
poke
  • 369,085
  • 72
  • 557
  • 602
user3479915
  • 5
  • 1
  • 4

2 Answers2

3
[x for x in a if x != '']

You can use this to filter the ''

EDIT considering saybyasachi's suggestion. Using the fact that all elements are strings, a more pythonic way to approach would be:

 [x for x in a if x]
sushant-hiray
  • 1,838
  • 2
  • 21
  • 28
  • 3
    Don't use `is` and `is not`, which test identity, when you want to test equality. This will only work if every empty string happens to be the same empty string. – DSM Mar 02 '14 at 18:03
  • 1
    @Sushant considering that we know that all elements are in fact strings, wouldn't you consider `[x for x in a if x]` to be more pythonic? – Guy Mar 02 '14 at 20:17
1

Like this, which retains any item with any sort of worthwhile value:

[item for item in array_name if item]
anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Your `for` loop can fail, as you're removing elements from the list you're iterating over. – DSM Mar 02 '14 at 18:02
  • [A bad idea](http://stackoverflow.com/questions/2541528/iterating-through-a-list-removing-items-some-items-are-not-removed). – poke Mar 02 '14 at 18:02
  • Test your first code with `['', '', 'foo']`. – Ashwini Chaudhary Mar 02 '14 at 18:02
  • @DSM but surely it is fine if I am not removing by the index, and with the added condition that I only do one action of appending or removing within that iteration? Please explain. – anon582847382 Mar 02 '14 at 18:11
  • If you remove the current item in an iteration, the next item in the list will be skipped. There’s no need “to be careful”; it’s just how it works, and why you shouldn’t edit a list while iterating over it. – poke Mar 02 '14 at 18:15
  • @AlexThornton: read the answers in poke's link, and try Ashwini's example. – DSM Mar 02 '14 at 18:15
  • @DSM ah. I see. Modifications have been made. At the end of the day, I'm still only a student. Thank you all for helping me to improve my answer and my own knowledge along. – anon582847382 Mar 02 '14 at 18:25