Python List Slicing with None as argument

后端 未结 4 601
旧时难觅i
旧时难觅i 2020-12-16 11:56

Via trial and error I found out that

my_list = range(10)
my_list[:None] == my_list[:]

I use this for django query sets so I can define a si

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 12:37

    Your way is fine, but I would prefer :

    some_queryset[:length] if length else some_queryset
    

    or

    some_queryset[:length] if length else some_queryset[:]
    

    which are readable with less knowledge of how slicing treats these special cases.

提交回复
热议问题