Search code examples
pythonlistcopying

getting list without k'th element efficiently and non-destructively


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.


Solution

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

    Is this what you want?