Paarudas
Paarudas

Reputation: 375

How to remove n number of elements from a list by index in Python?

Let us assume,

g = ['1', '', '2', '', '3', '', '4', '']

I want to delete all '' from g, where i have to get

g = ['1', '2', '3', '4']

Upvotes: 1

Views: 202

Answers (4)

wim
wim

Reputation: 362647

If your list is all strings, use the fact that empty sequences are false in an if statement:

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> [x for x in g if x]
['1', '2', '3', '4']

Otherwise, use [x for x in g if x != '']

Upvotes: 5

pillmuncher
pillmuncher

Reputation: 10162

If the '' are always and only at even numbered indices, then here's a solution that actually deletes the items:

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> g[::2]
['1', '2', '3', '4']
>>> g[1::2]
['', '', '', '']
>>> del g[1::2]  #  <-- magic happens here.
>>> g
['1', '2', '3', '4']

The magic, of course is a slice assignment.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304147

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> filter(None, g)
['1', '2', '3', '4']

Help on built-in function filter in module `__builtin__`:

filter(...)
filter(function or None, sequence) -> list, tuple, or string

   Return those items of sequence for which function(item) is true.  If
   function is None, return the items that are true.  If sequence is a tuple
   or string, return the same type, else return a list.

You can also use a list comprehension if you prefer

>>> [x for x in g if x!=""]
['1', '2', '3', '4']

Upvotes: 5

Interrobang
Interrobang

Reputation: 17434

new_g = [item for item in g if item != '']

Upvotes: 4

Related Questions