list extend() to index, inserting list elements not only to the end

后端 未结 1 1397
太阳男子
太阳男子 2020-12-15 03:52

I\'m looking for the most pythonic way to implement a version of the list extend function, where it extends to a given index instead of the end of the list.

相关标签:
1条回答
  • 2020-12-15 04:39

    Sure, you can use slice indexing:

    a_list[1:1] = b_list
    

    Just to demonstrate the general algorithm, if you were to implement the my_extend function in a hypothetical custom list class, it would look like this:

    def my_extend(self, other_list, index):
        self[index:index] = other_list
    

    But don't actually make that a function, just use the slice notation when you need to.

    0 讨论(0)
提交回复
热议问题