Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)]
k=1
l_without_num=l[:]   # or list(l) if you prefer
l_without_num.pop(k)

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