26

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.

  • another way I thought of doing this is as follows: # assume k is the element to be excluded filter(lambda x: x[0] != k, l) is this respectable? are there better ways? –  Jan 26 '10 at 20:40
  • Can you explain me what the expected result is? "NameError: name 'copy' is not defined" – Pepijn Jan 26 '10 at 20:44
  • 2
    It's not clear to me what the result of this operation is supposed to be. The implementation you posted constructs but doesn't use 3 different copies of the original list, missing three different elements. Can you clarify your goals? – Will McCutchen Jan 26 '10 at 20:46

7 Answers7

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

Is this what you want?

Chris B.
  • 85,731
  • 25
  • 98
  • 139
9

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
  • 309
  • 1
  • 6
2
l=[('a', 1), ('b', 2), ('c', 3)]
k=1
l_without_num=l[:]   # or list(l) if you prefer
l_without_num.pop(k)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2
new = [l[i] for i in range(len(l)) if i != k]
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1
#!/bin/bash
`python -c "'\n'.join(mylist[:])" 2>NULL | sed '/mybadelement/d'`

lol

Dan Mantyla
  • 1,840
  • 1
  • 22
  • 33
1

Using difference operator on sets:

list(set(l).difference([l[k]])

l=[('a', 1), ('b', 2), ('c', 3)]
list(set(l).difference([l[1]]))
[('a', 1), ('c', 3)]
rajivRaja
  • 527
  • 3
  • 6
  • 16
0

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
  • 198,619
  • 38
  • 280
  • 391