Head and tail in one line

后端 未结 5 636
独厮守ぢ
独厮守ぢ 2020-11-29 00:32

Is there a pythonic way to unpack a list in the first element and the \"tail\" in a single command?

For example:

>> head, tail = **some_magic a         


        
5条回答
  •  难免孤独
    2020-11-29 01:12

    For O(1) complexity of head,tail operation you should use deque however.

    Following way:

    from collections import deque
    l = deque([1,2,3,4,5,6,7,8,9])
    head, tail = l.popleft(), l
    

    It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.

提交回复
热议问题