views:

110

answers:

5

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)
  l_without_num.remove(elt)

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.

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

Is this what you want?

Chris B.
+1, definitely heads and shoulders the best way! Why iterate when you can slice and concatenate?-)
Alex Martelli
+2  A: 

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.

vogonistic
A: 

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. :-)

ephemient
Maybe there should be an ifilter in there? :)
gnibbler
Would downvoters please comment why? The first solution is equivalent to the leading answer, in results and algorithmic complexity.
ephemient
+1  A: 
l=[('a', 1), ('b', 2), ('c', 3)]
k=1
l_without_num=l[:]   # or list(l) if you prefer
l_without_num.pop(k)
gnibbler
A: 
new = [l[i] for i in range(len(l)) if i != k]
inspectorG4dget