I have a list in python and I’d like to iterate through it, and selectively construct a list that contains all the elements except the current k’th element. one way I can do it is this:

l = [('a', 1), ('b', 2), ('c', 3)]
for num, elt in enumerate(l):
  # construct list without current element
  l_without_num = copy.deepcopy(l)

but this seems inefficient and inelegant. is there an easy way to do it? note I want to get essentially a slice of the original list that excludes the current element. seems like there should be an easier way to do this.

thank you for your help.

l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = l[:k] + l[(k + 1):]

Is this what you want?

It would help if you explained more how you wanted to use it. But you can do the same with list comprehension.

l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = [elt for num, elt in enumerate(l) if not num == k]

This is also more memory efficient to iterate over if you don’t have to store it in l_without_num.

l=[('a', 1), ('b', 2), ('c', 3)]
l_without_num=l[:]   # or list(l) if you prefer

new = [l[i] for i in range(len(l)) if i != k]

`python -c "'\n'.join(mylist[:])" 2>NULL | sed '/mybadelement/d'`


Using difference operator on sets:


l=[('a', 1), ('b', 2), ('c', 3)]
[('a', 1), ('c', 3)]

Probably not the most efficient, but the functional programmer in me would probably write this.

import operator
from itertools import *
def inits(list):
    for i in range(0, len(list)):
        yield list[:i]
def tails(list):
    for i in range(0, len(list)):
        yield list[i+1:]
def withouts(list):
    return imap(operator.add, inits(list), tails(list))

for elt, without in izip(l, withouts(l)):

import functools, operator
for elt in l:
    without = filter(functools.partial(operator.ne, elt), l)

I don’t think it’s the right thing to do, but it’s short. 🙂