How to remove an element from a list by index

后端 未结 18 3361
闹比i
闹比i 2020-11-22 03:22

How do I remove an element from a list by index in Python?

I found the list.remove method, but say I want to remove the last element, how do I do this?

18条回答
  •  我寻月下人不归
    2020-11-22 03:59

    As previously mentioned, best practice is del(); or pop() if you need to know the value.

    An alternate solution is to re-stack only those elements you want:

        a = ['a', 'b', 'c', 'd'] 
    
        def remove_element(list_,index_):
            clipboard = []
            for i in range(len(list_)):
                if i is not index_:
                    clipboard.append(list_[i])
            return clipboard
    
        print(remove_element(a,2))
    
        >> ['a', 'b', 'd']
    

    eta: hmm... will not work on negative index values, will ponder and update

    I suppose

    if index_<0:index_=len(list_)+index_
    

    would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension.

    pondering

提交回复
热议问题