0

I have a list with integers, in which every second int is zero (0), like this:

mylist = [1,0,2,0,3,0,4,0]

I can only check single positions like so:

for i in range(0, len(mylist)):
     if i in mylist:
          #do something here

I am trying to check for two positions at every loop, so if the loop finds for example "2, 0" in mylist, it will be able to remove those two ints.

Any suggestion will be appreciated.

CDoc
  • 379
  • 3
  • 16

2 Answers2

2

Since the values between the 0s are unique, you can simply use list.index to find the target value and then use del to delete this value and the next one from the list:

>>> my_list = [1,0,2,0,3,0,4,0]
>>> my_index = my_list.index(3)
>>> del my_list[my_index:my_index+2]
>>> my_list
[1, 0, 2, 0, 4, 0]
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
1

Here is an example if you wanna remove the sequence (2,0), taking into account flatten method mentionned below:

from itertools import izip, chain

>>> list(chain(*[[u,v] for u,v in izip(*[iter(mylist)]*2) if (u,v)!=(2,0)]))
[1, 0, 3, 0, 4, 0]

All credits goes to:

Creating a python dictionary from a line of text

Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
  • 1
    Just add some flattening to this and I think it's the most flexible here... – Jon Clements Aug 02 '17 at 15:56
  • @JonClements Flexible, but perhaps a little overkill for the question, given their values apart from `0`s are unique? Also `itertools.chain.from_iterable()` is the Pythonic way to flatten – Chris_Rands Aug 02 '17 at 16:02
  • @JonClements - Indeed, the question's subject line suggests checking for an arbitrary sequence of values (not even necessarily pairs). As long as these checks are meant not to be overlapping, this is a nice approach. I will say it's a little arcane, especially for Python beginners. I don't think there would be anything wrong with explicit looping instead. – John Y Aug 02 '17 at 16:03
  • Did not know the values are unique. Chris_Rabds answer is not ninja-ic and does well the job, despite no one liner. – Colonel Beauvel Aug 02 '17 at 16:06
  • Hm. I'm kind of disappointed by the edit. Using `sum()` as a "list concatenator" is arguably abuse of the function. As @Chris_Rands notes, this should be done with `itertools.chain.from_iterable()` (or `itertools.chain()` with the `*` operator). – John Y Aug 02 '17 at 16:10
  • @JohnY yeah... even a nested list-comp would be better than sum :) – Jon Clements Aug 02 '17 at 16:11
  • I suspect for what looks like an assignment - Chris' answer is what's expected though... – Jon Clements Aug 02 '17 at 16:12